23 Design Patterns (1): Singleton Pattern

Definition: Ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.

Type: Create Class Pattern

Class Diagram:

Class diagram knowledge points:

1. The class diagram is divided into three parts, followed by class name, attribute, method

2. Beginning with << and ending with >> as comments

3. The modifier + stands for public, - stands for private, # stands for protected, and nothing means the package is visible.

4. Underlined properties or methods represent static.

5. Friends who are not familiar with the relationship of objects in class diagrams can refer to the article: Relationship of Classes in Design Patterns .

The singleton pattern should be the simplest of the 23 design patterns. It has the following elements:

  • private constructor
  • Private static reference to own instance
  • A static public method that returns its own instance

        The singleton pattern is divided into two types according to the time of instantiating the object: one is the hungry singleton, and the other is the lazy singleton. Hungry-style singleton instantiates an object and hands it to its own reference when the singleton class is loaded; while lazy-style singleton instantiates an object when calling the get instance method. code show as below:

Hungry singleton

[java]  view plain
  1. publicclass Singleton {   
  2.     privatestatic Singleton singleton = new Singleton();   
  3.     private Singleton(){}  
  4.     publicstatic Singleton getInstance(){   
  5.         return singleton;  
  6.     }  
  7. }  

lazy singleton

[java]  view plain
  1. publicclass Singleton {   
  2.     privatestatic Singleton singleton;   
  3.     private Singleton(){}  
  4.       
  5.     publicstaticsynchronized Singleton getInstance(){    
  6.         if(singleton==null){  
  7.             singleton = new Singleton();  
  8.         }  
  9.         return singleton;  
  10.     }  
  11. }  

Advantages of the singleton pattern:

  • There is only one object in memory, saving memory space.
  • Avoiding frequent creation and destruction of objects can improve performance.
  • Avoid multiple occupation of shared resources.
  • Can be accessed globally.

Applicable scenarios: Due to the above advantages of the singleton pattern, it is a design pattern that is used more in programming. Here's a summary of what I know of scenarios that are suitable for using the singleton pattern:

  • Objects that need to be frequently instantiated and then destroyed.
  • Objects that take too much time or resources to create, but are often used.
  • A stateful utility class object.
  • Objects that frequently access databases or files.
  • And all the other scenarios I haven't used that require only one object.

Notes on the singleton pattern:

  • You can only use the methods provided by the singleton class to get the singleton object, do not use reflection, otherwise a new object will be instantiated.
  • Do not do the dangerous operation of disconnecting singleton class objects from static references in the class.
  • When using a singleton to use shared resources in multiple threads, pay attention to thread safety issues.

关于Java中单例模式的一些争议:

单例模式的对象长时间不用会被jvm垃圾收集器收集吗

        看到不少资料中说:如果一个单例对象在内存中长久不用,会被jvm认为是一个垃圾,在执行垃圾收集的时候会被清理掉。对此这个说法,笔者持怀疑态度,笔者本人的观点是:在hotspot虚拟机1.6版本中,除非人为地断开单例中静态引用到单例对象的联接,否则jvm垃圾收集器是不会回收单例对象的。

对于这个争议,笔者单独写了一篇文章进行讨论,如果您有不同的观点或者有过这方面的经历请进入文章单例模式讨论篇:单例模式与垃圾收集参与讨论。

 

在一个jvm中会出现多个单例吗

        在分布式系统、多个类加载器、以及序列化的的情况下,会产生多个单例,这一点是无庸置疑的。那么在同一个jvm中,会不会产生单例呢?使用单例提供的getInstance()方法只能得到同一个单例,除非是使用反射方式,将会得到新的单例。代码如下

[java]  view plain
  1. Class c = Class.forName(Singleton.class.getName());  
  2. Constructor ct = c.getDeclaredConstructor();  
  3. ct.setAccessible(true);  
  4. Singleton singleton = (Singleton)ct.newInstance();  

这样,每次运行都会产生新的单例对象。所以运用单例模式时,一定注意不要使用反射产生新的单例对象。

 

懒汉式单例线程安全吗

        It is mainly based on some opinions on the Internet. The lazy singleton mode is thread-unsafe. Even adding the synchronized keyword to the method of instantiating an object is still dangerous. However, after coding and testing , I found that adding the synchronized keyword After modification, although it has a partial impact on performance, it is thread-safe and does not cause multiple objects to be instantiated.

 

Are there only two types of singleton mode: hungry and lazy?

        Hungry-style singleton and lazy-style singleton are just two more mainstream and commonly used singleton pattern methods. In theory, any design pattern that can implement a class with only one instance can be called the singleton pattern.

 

Can a singleton class be inherited?

        Hungry-style singletons and lazy-style singletons are not inheritable because their constructors are private, but many other singleton patterns can be inherited, such as registered singletons.

 

Is Hungry-style singleton better or lazy-style singleton better?

        In java, hungry singleton is better than lazy singleton. In C++, lazy singletons are generally used.

 

The singleton mode is relatively simple, so I will not demonstrate the code example here.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326577599&siteId=291194637