A singleton pattern of design patterns

Source: Internet
Author: User

1. Concept:

Single-Case mode:

(1), en:ensure A class have only one instance,and provide a global point of access to it.

(2), CH: Ensure that a class has only one instance , and instantiate itself and provide this instance to the system as a whole.

Common class diagrams for singleton patterns:



2. Example:

Singleton class:

Package Dim.singleton;public class Singleton {private  static final singleton singleinstance=new Singleton ();/** * Private constructor */public    Singleton () {//TODO auto-generated constructor StubSystem.out.println ("constructor"); public static Singleton Getsingletonins () {return singleinstance;} public static void SayHello () {System.out.println ("Hello I am Singleton!");}}


test Class Code:

Package Dim.singleton;public class Testlsingletonclass {/** * @param args */public static void main (string[] args) {single ton. Getsingletonins (); Singleton.sayhello (); }}

Operation Result:

constructor Hello I am Singleton!



Look at the result as if the constructor is called only once, and the code for the Singleton class is similar to the singleton pattern. If you modify the test class code as follows:

Package Dim.singleton;public class Testlsingletonclass {/** * @param args */public static void main (string[] args) {single ton. Getsingletonins ();       New Singleton ();//Try new one object Singleton.sayhello (); }}

Operation Result:

Constructor constructor Hello I am Singleton!
as you can see from the results, Singleton is instantiated two times and can be manipulated in other classes as well. Where is the problem??

Look closely at the class diagram: The constructor in Singleton is-Singleton (). The constructors in the singleton class above are public "for the sake of being impressed, the constructor is deliberately set to public"



3, the type of the singleton mode and the general code:(1) A Hungry man mode:

/** * Single-mode generic code  */private  static final Singleton singleinstance=new Singleton ();/** * Private Constructor     */ Private Singleton () {//TODO auto-generated constructor StubSystem.out.println ("constructor");} public static Singleton Getsingletonins () {return singleinstance;}


(2) lazy mode:

Private Singleton () {System.out.println ("singleton!");} Public    static Singleton getinstance (String teststr) {synchronized (Singleton.class) {if (singleton==null) { Singleton=new Singleton ();} return singleton;}}

Why do you add synchronized here? What happens if you don't add.

If the code block is not synchronized. When dealing with multithreading, when the system pressure increases, a thread determines that Singleton is null, and then initializes the Singleton. If the A is not initialized, Singleton is empty at this time, B thread now determines that singleton is null, you can initialize the singleton. The singleton has been initialized two times, which violates the principle of a single case to ensure that there is only one instance of a class.


Multithreaded Access Examples:

"1", the method does not increase the internal synchrogazed.

Package Dim.singleton.lazy;public class Singleton {private static singleton singleton=null;private String name= ""; private int Num=0;private Singleton () {System.out.println ("lazy singleton!");} Public    static Singleton getinstance (String teststr) {System.out.println ("Come in=" +teststr); if (singleton==null) {System.out.println ("Come in========" +teststr); singleton=new Singleton ();} return singleton;} public int Getnum () {return Num;} public void setnum (int num) {num = num;} public void Setnameofsingle (String Name) {this. Name=name;} Public String Getnameofsingle () {return Name;}}

Test class:

package dim.singleton.lazy;import java.io.ioexception;import Java.nio.charbuffer;import Javax.swing.plaf.SliderUI ;p Ublic class Testsingletonclass {/** * @param args */public static void main (string[] args) {//TODO auto-generated Metho D stubrunnable testruna=new Runnable () {@Overridepublic void run () {while (true) {//TODO auto-generated method Stubsinglet On.getinstance ("A"); try {thread.sleep (1);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}; Thread testthreada=new thread (Testruna); Testthreada.start (); Runnable testrunb=new Runnable () {@Overridepublic void run () {while (true) {//TODO auto-generated method Stubsingleton.getinstance ("B"); try {thread.sleep (1);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}; Thread testthreadb=new thread (TESTRUNB); Testthreadb.start ();}} 


output: ======== indicates that a null judgment is passed and can be initialized.

Run multiple attempts:





Visible:

The singleton has been initialized two times, which violates the principle of a single case to ensure that there is only one instance of a class.


"2", method internal increase synchrogazed

Package Dim.singleton.lazy;public class Singleton {private static singleton singleton=null;private String name= ""; private int Num=0;private Singleton () {System.out.println ("lazy singleton!");} Public    static Singleton getinstance (String teststr) {synchronized (Singleton.class) {System.out.println ("Come in= "+teststr"), if (singleton==null) {System.out.println ("Come in========" +teststr); singleton=new Singleton ();} return singleton;}} public int Getnum () {return Num;} public void setnum (int num) {num = num;} public void Setnameofsingle (String Name) {this. Name=name;} Public String Getnameofsingle () {return Name;}}

multiple runs of discovery, Singleton is always initialized once.


4. Description:


The constructor of the singleton mode is to add private to ensure that there is only one instance of a class.


Singleton mode usage Scenarios:

(1), need to define a large number of today's variables and static methods.

(2), projects, shared access points, or shared data.

(3), when you need to create an object that consumes more resources.

(4), Other:

Disadvantages of the Singleton pattern:

(1), difficult to expand.

(2), in conflict with the principle of single responsibility.

(3), other.


Resources:

"Zen of Design Patterns"



RELATED links:

Single duty principle of six principles of design pattern

The six principles of design pattern on the Richter scale substitution principle

The principle of dependency inversion in six principles of design pattern

The principle of interface isolation of six principles of design pattern

Design pattern Six principles of the Dee-mitt law

The principle of opening and closing of six principles of design pattern


Some shortcomings, many corrections, thank you!



A singleton pattern 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.