📙
Design Pattern
  • Introduction
  • 0. About Design Pattern
  • 1. Singleton
  • 1.1 Eager Singleton (a.k.a Pessimistic Lock Singleton)
  • 1.2 Lazy Singleton (a.k.a Optimistic Lock Singleton)
  • 1.3 理解Singleton
  • 1.4 Cache Singleton
  • 1.5 Extend Singleton
  • 1.6 Double Check and Lock Singleton
  • 1.7 Lazy Initialization Holder Class
  • 1.8 Enum Singleton
  • 1.9 Conclusion
  • 2. Factory
  • 2.1 Simple Factory
  • 2.2 Factory
  • 2.3 Abstract Factory
  • 2.4 Conclusion
Powered by GitBook
On this page

Was this helpful?

1.1 Eager Singleton (a.k.a Pessimistic Lock Singleton)

定義: Eager Singleton, 有時又稱悲觀鎖(pessimistic lock)單例, 亦即在類別中把實例宣告為私有靜態的屬性, 以下直接以程式說明.

package idv.design.pattern.singleton.eager;

/**
 * @author Carl Lu
 */
public class Singleton {

    /*
     * This is also called "pessimistic lock singleton".
     */

    /*
     * Define a variable for saving instance, new the instance here.
     * The JVM will guarantee that the class will be instantiated for only one time,
     * so this way is thread-safe.
     */
    private static final Singleton uniqueInstance = new Singleton();

    /*
     * The constructor should be private so that we can control the instance number.
     */
    private Singleton() {

    }

    /*
     * Need to define a method for providing class instance to clients.
     *
     * @return Singleton singleton instance.
     */
    public static Singleton getInstance() {
        return uniqueInstance;
    }

}
Previous1. SingletonNext1.2 Lazy Singleton (a.k.a Optimistic Lock Singleton)

Last updated 5 years ago

Was this helpful?

原始碼

點我