Singleton design pattern (the Singleton)

Singleton (Singleton Pattern) is one of the easiest in Java design patterns. This type of design pattern belongs create schema , which provides the best way to create objects. This model involves a single class that is responsible for creating your own objects, while ensuring that only a single object is created. This class provides the only way to access the object can directly access, no instance of the object class.

Singleton five kinds created:

  • Starving type : class initialization time, the object will load immediately, inherently thread-safe, high call efficiency.
  • Lazy style : When class is initialized, initialize the object does not really need to use the time will go to create the object with lazy loading functionality.
  • Static inner classes manner : a combination of lazy and hungry style of Han respective advantages, the real needs when the object will load, load class is thread-safe.
  • Singleton enumeration : enum achieve Singleton pattern, simple, high efficiency call, the enumeration itself is a single case, to provide protection fundamentally by the JVM, through reflection and avoid de-serialization of vulnerability, disadvantage is that there is no delay loading .
  • Dual detection mode : (JVM itself because of reordering may be initialized appear more than once).

 Codes are as follows:

// hungry Chinese-style 
public  class SingletonDemo01 {
     // When the class is initialized, the object will load immediately, thread inherently safe, high efficiency calls 
    Private  static SingletonDemo01 singletonDemo01 = new new SingletonDemo01 ();
     Private SingletonDemo01 () { 
        System.out.println ( " SingletonDemo01 initialization " ); 
    } 
    public  static SingletonDemo01 the getInstance () { 
        System.out.println ( " the getInstance " );
         return singletonDemo01; 
    } 
    public  static  void main (String [] args) { 
        SingletonDemo01 S1 = SingletonDemo01.getInstance();
        SingletonDemo01 s2 = SingletonDemo01.getInstance();
        System.out.println(s1 == s2);//结果为ture
    }
 
}

 

// lazy-style 
public  class SingletonDemo02 {
     // When the class is initialized, the object is not initialized, when the real need to use will create the right. 
    Private  static SingletonDemo02 singletonDemo02; 
 
    Private SingletonDemo02 () { 
    } 
    public  the synchronized  static SingletonDemo02 the getInstance () {
         IF (singletonDemo02 == null ) { 
            singletonDemo02 = new new SingletonDemo02 (); 
        } 
        return singletonDemo02; 
    } 
 
    public  static  void main (String [] args) { 
        S1 SingletonDemo02 = SingletonDemo02.getInstance();
        SingletonDemo02 s2 = SingletonDemo02.getInstance();
        System.out.println(s1 == s2);//结果为true
    }
}

 

// static inner classes embodiment 
public  class SingletonDemo03 {
     Private SingletonDemo03 () { 
           System.out.println ( "initialization .." ); 
    } 
 
    public  static  class SingletonClassInstance {
         Private  static  Final SingletonDemo03 singletonDemo03 = new new SingletonDemo03 (); 
    } 
 
    // methods do not synchronization 
    public  static SingletonDemo03 the getInstance () { 
        System.out.println ( "the getInstance" );
         return SingletonClassInstance.singletonDemo03; 
    } 
 
    public static  void main (String [] args) { 
        SingletonDemo03 S1 = SingletonDemo03.getInstance (); 
        SingletonDemo03 S2 = SingletonDemo03.getInstance (); 
        System.out.println (S1 == S2); // result is to true 
    } 
} 
//
Advantages : taking into account the lazy memory optimization mode (when using the initialization) and safety starving mode (not reflected invasion).
// Disadvantages: need two classes to do this, although the object does not create static inner classes, but its Class object will still be created, and the object is part of a permanent band.
 

 

//枚举单例式
public class User {
    public static User getInstance() {
        return SingletonDemo04.INSTANCE.getInstance();
    }
 
    private static enum SingletonDemo04 {
        INSTANCE;
        // 枚举元素为单例
        private User user;
 
        private SingletonDemo04() {
            System.out.println("SingletonDemo04");
            user = new User();
        }
 
        public User getInstance() {
            return user;
        }
    }
 
    public static void main(String[] args) {
        User u1 = User.getInstance();
        User u2 = User.getInstance();
        System.out.println(u1 == u2);//结果为true
    }
}

 

//双重检测方式
public class SingletonDemo04 {
    private SingletonDemo04 singletonDemo04;
 
    private SingletonDemo04() {
 
    }
 
    public SingletonDemo04 getInstance() {
        if (singletonDemo04 == null) {
            synchronized (this) {
                if (singletonDemo04 == null) {
                    singletonDemo04 = new SingletonDemo04();
                }
            }
        }
        return singletonDemo04;
    }
 
}

 

advantage:

  • In the single-mode embodiment, only a single example of embodiment the activity of singleton instances of all classes obtained are the same instance. This prevents other objects instantiated on their own to ensure that all have access to an instance of an object. 
  • Singleton pattern having a certain flexibility, their class to instantiate the control process, based on a corresponding instance stretchability in the process of change.
  • It provides controlled access to the only instance.
  • Because there is only one object in system memory, so you can save system resources when the object is created and destroyed frequently singleton pattern certainly can improve system performance.
  • It allows a variable number of instances.
  • Avoid multiple assignment of shared resources.


Disadvantages:

  • Not to change the subject, if the same type of object always occurs in a different embodiment with scene change, a single case will cause erroneous data can not be saved in another state.
  • Since there is no single model abstraction layer interest, thus expanding the singleton class have great difficulty.
  • Responsibilities singleton class too heavy, contrary to the "principle of the single function" to some extent.
  • Single cases of abuse will bring some negative issues, in order to save resources such as database connection pool object as a singleton class design, may lead to too many programs shared object connection pool connection pool overflow occurs; if instantiated objects for a long time not being used, the system will be considered garbage to be collected, which will result in the loss of the object's state.

 

Precautions:

  • Singleton can not be created using a reflective mode, otherwise it will instantiate a new object.
  • Note thread-safety issues when using lazy singleton.
  • Singleton and lazy singleton constructor is private, so can not be inherited, some cases of single mode can be inherited (e.g., register-based mode).


Scenario:
Singleton pattern allows the creation of an object, thus saving memory, speed up the access speed of the object, the object needs to be the occasion for public use.

  • A plurality of modules connected to the same object using a data source.
  • Require frequent instantiate an object and then destroyed.
  • When you create an object too time-consuming or consuming too many resources, but frequently used objects.
  • Stateful tools object.
  • Object databases or frequently accessed files.
  • In the case of resource sharing, to avoid loss of performance or the like due to resource operation result. Such as log files, application configuration.
  • If the control resource, to facilitate mutual communication between the resources. Such as thread pool.


For example:

  • External Resources: Each computer has a number of printers, but only one PrinterSpooler, to avoid two print jobs simultaneously output to the printer.
  • 内部资源:大多数软件都有一个(或多个)属性文件存放系统配置,这样的系统应该有一个对象管理这些属性文件。
  • Windows的TaskManager(任务管理器)就是典型的单例模式,想想看,你能同时打开两个windows task manager吗? 
  • windows的Recycle Bin(回收站)也是典型的单例模式。在整个系统运行过程中,回收站一直维护着仅有的一个实例。
  • 网站的计数器,一般也是采用单例模式实现,否则难以同步。
  • 应用程序的日志应用,一般都是使用单例模式实现,因为共享的日志文件一直处于打开状态,因此只能有一个实例去操作,否则不方便追加内容。
  • Web应用的配置对象的读取,一般也应用单例模式,因为配置文件是共享的资源。
  • 数据库连接池的设计一般是采用单例模式,因为数据库连接是一种数据库资源。数据库软件系统中使用数据库连接池,主要是节省打开或者关闭数据库连接所引起的效率损耗,这种效率上的损耗还是非常昂贵的,使用单例模式来维护,可以大大降低这种损耗。
  • 多线程的线程池的设计一般也是采用单例模式,因为线程池要方便对池中的线程进行控制。
  • 操作系统的文件系统,也是单例模式实现的具体例子,一个操作系统只能有一个文件系统。

Guess you like

Origin www.cnblogs.com/lucky1024/p/11511842.html