Zen of design pattern--Singleton mode

Source: Internet
Author: User

Single

Example Pattern definition:
Make sure that there is only one instance of a class, and instantiate it yourself and provide this instance to the entire system.

The ancient emperor should be a singleton, see Code

Package com.sdkd.hms; Public classEmperor {Private StaticFinal Emperor Emperor =NewEmperor ();Private Emperor(){    } Public StaticEmperorgetinstance(){returnEmperor } Public Static void say() {System. out. println ("I am the emperor HMS."); }}----------package com.sdkd.hms; Public classClient { Public Static void Main(string[] args) { for(intDay =0; Day <3;            ++day) {Emperor Emperor = emperor.getinstance ();        Emperor.say (); }    }}/ * I am Emperor HMS I am Emperor HMS I am Emperor Hms*/

The implementation of the singleton mode is more fixed, it is good to remember, its construction method is private, only in the internal instantiation.

Here is the general code for it

public   Class  singleton{private  static  final    Singleton Singleton = new  Singleton (); private  singleton  () {} public  static  Singleton getsingleton  () {return  Singleton; } //class. Try to be static  public  static  void  dosomething  () {}}  

Analysis of advantages and disadvantages of the singleton pattern (emphasis is on disadvantage)
Advantages:
1, the singleton mode in memory only one instance, reduce memory expenditure, especially an object needs to be frequently created, destroyed
2, because the singleton mode only generates one instance, so the performance cost of the system is reduced.
3, the singleton mode can avoid the multiple occupancy of the resource. For example, a write file action, because only one instance exists in memory, avoid simultaneous write operations to the same resource file.
4, the singleton mode can set the global access point, optimize and share the resource access, for example, can design a singleton class, responsible for all the data table mapping processing.
Disadvantages:
1, single-case mode is generally not interface, expansion is very difficult.
2. The singleton mode is unfavorable to the test. In a parallel development environment, if Singleton mode is not completed, it cannot be tested, and no interface can be used to virtual an object in a mock manner.
3. There is a conflict between the singleton mode and the single duty principle. A class should only implement a single logic, not whether it is a singleton, is not a single case depends on the environment, the singleton mode "to be single" and business logic into a class.

Scenario for a singleton pattern:
1. Environments that require unique serial number generation
2. Need a shared access point or shared data in the project
3. Creating an object consumes too much resources, such as accessing IO and database resources.
4, need to define a large number of static variables and static methods (tool Class) of the environment

Considerations for single-instance mode
1, Thread unsafe single case

public   Class  singleton{private  static  final Singleton Singleton = null  private  singleton  () {} public  static  Singleton getsingleton  () {if  (Singleton =        = null ) singleton = new  Singleton (); return     Singleton; } //class. Try to be static  public  static  void  dosomething  () {}}  

For example, if a thread a executes Singleton = new Singleton () but has not yet obtained the object (which takes time), the second thread B is also executing, executing to (Singleton = = null) judgment, then B gets the judging condition to be true, and then continues to run. When A and B both acquire an object, a bug is created.

You just need to change the code just like this.

public static synchronized Singleton getSingleton(){        if(singleton == null) singleton = new Singleton();        return Singleton;    }----------2、需要考虑对象的复制情况,在java中对象是默认不可复制的,若实现了Cloneable接口,并实现了clone方法,则可以直接通过对象复制方式创建一个新对象。这个问题的的最好的解决办法就是----不要实现Cloneable方法。

~~

Zen of design pattern--Singleton mode

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.