Design Pattern learning-Singleton pattern

Source: Internet
Author: User

Definition: Singleton Pattern: Ensure a class has only one instance, and provide a global point of access to it.(Make sure that a class has only one instance and the instance is self-instantiated and provided to the entire system)
I. ExampleFor example, a dynasty can only have one emperor: Therefore, we require a class to generate only one object (Emperor). How can we make one class generate only one object? We know that when we use the new keyword to create an object, the corresponding constructor will be called according to the input parameters. If we set the constructor to private, can we not prohibit external object creation? We design two classes in this way: Emperor represents the Emperor class, and Minister represents the Minister class. The Code is as follows:

Public class Emperor {private static final Emperor emperor = new Emperor (); // Initialize an Emperor private Emperor () {} public static emperor getInstance () {return Emperor ;} // The Emperor speaks public static void say () {System. out. printIn ("I'm Qin Shihuang ..... ");}}
By defining a constructor with private access permissions, other classes are prevented from creating a new object, while Emperor itself can create a new object, other classes can use getInstance to obtain the same object.
The sub-category is as follows:
public class Minister{    public static void mian(String[] args){        for(int day=0; day<3; day++){            Emperor emperor = Emperor.getInstance();            emperor.say();        }    }}
Output result:
I'm Qin Shihuang .....
This is the singleton mode.

The Singleton class is called a Singleton class. The private constructor ensures that only one instance is generated in an application, it is self-instantiated (new Singleton () is used in Singleton ()). Ii. Common Code for Singleton mode:
Public class Singleton {private static final Singleton singleton = new Singleton (); // restrict the generation of multiple objects private Singleton () {}// use this method to obtain the Instance Object public static Singleton getSingleton () {return singleton;} // other methods in the class, try to static public static void doSomething (){}}
Iii. Advantages of Singleton mode:● Because the singleton mode only has one instance in the memory, the memory consumption is reduced.
● Because the singleton mode only generates one instance, the system performance overhead is reduced. For example, when an object requires more resources, for example, when reading the configuration and generating other dependent objects, you can directly generate a single-instance object during application startup, and then use the permanent memory resident method to solve the problem.
● The Singleton mode can avoid multiple resource occupation ● In the singleton mode, you can set global access points in the system to optimize and share resource access. For example, you can design a singleton class, maps all data tables. Iv. disadvantages of Singleton mode:● The Singleton mode is generally no excuse, and expansion is difficult because it does not make any sense for the singleton mode. It requires "self-instantiation" and provides a single instance, however, excuses or abstract classes cannot be instantiated (except in special cases)
● The Singleton mode is unfavorable for testing ● The Singleton mode conflicts with the single responsibility principle. A class should only implement one logic, regardless of whether it is Singleton, whether a singleton is required depends on the environment. The Singleton mode integrates the "Singleton" and business logic into a class.
V. Use Cases of Singleton mode:● Environment where a unique serial number is required ● A shared access point or shared data is required for the entire project. For example, a counter on a web page can be recorded in the database every time a refresh is made, maintain the counter value in singleton mode and ensure thread safety.
● Creating an object consumes too many resources, such as accessing IO and database resources.
● Scenarios where a large number of static constants and static methods need to be defined (of course, they can be directly declared as static), for example: tool class
Vi. Considerations for Singleton mode:When the concurrency is high, pay attention to the thread synchronization problem in singleton mode.
public class Singleton{    private static Singleton singleton = null;    private Singleton(){}    public static Singleton getSingleton(){        if(singleton == null){            singleton = new Singleton();        }        return singleton;    }}
In the case of low concurrency in the above Code, no problem will occur. If the system pressure increases and the concurrency increases, multiple instances may exist in the memory. Why? For example, if A thread A executes to singleton = new Singleton (), but has not yet obtained the object, the second thread B is also executing, and executes the if (singleton = null) Judgment, at this time, the judgment condition obtained by B is true, so we can continue to run it. Thread A obtains an object, and thread B also obtains an object. There are two objects in the memory !!
Solution: there are many ways to solve thread insecurity. You can add the synchronized keyword before the getSingleton method, or add synchronized in the getSingleton method, but none of them are the best Singleton mode.
We recommend that you use the following method: Singleton mode Common Code. This method becomes a hungry Singleton.
Next, we need to consider object replication. Objects in Java cannot be copied by default. If the Cloneable interface is implemented and the clone method is implemented, you can directly create a new object through the object replication method, object replication does not require calling class constructor. Therefore, objects can still be copied even if they are private constructor.
The best way to solve this problem is to avoid the Cloneable interface in advance for the singleton class!





Thank you for your reprinting.
Mr. Fu: Read the Zen of design patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.