Java design mode _single (Singleton design mode)

Source: Internet
Author: User

Design Patterns: The most effective way to solve a class of problems, there are 23 design patterns in Java

One, single example design mode overview:

1, solve a class in memory only one object (to ensure that a class has only one instance, and provide a access to his global access point)   
2, to ensure that the object is unique:
1. To prevent other programs from creating such objects too much, first prohibit other programs from establishing such objects
2. In order for other programs to have access to the class object, in this class, customize an Object
3. In order to facilitate the access of other programs to the custom object, you can provide some external access methods

3, the Code implementation steps:

1. Privatize the constructor
2. Create an object of this class in a class
3. Provide a static punk to the outside gets the object instance

4. Two ways of realization:
1. A Hungry man type
2, lazy-type

Second, a hungry man type:

This is the first initialization of the object, called: a Hungry Man-type single into memory, has created the object (development of general use this, simple and secure)

1  Public classSingleDemo1 {2      Public Static voidMain (string[] args) {3Single S1 = Single.getinstance ();//There is a S1 reference in the main function that gets the address of the single object,4     }5 }6 classsingle{7     PrivateSingle () {}//privatize constructors to keep other programs from building objects8 9     Private StaticSingle S =NewSingle ();//The following static method accesses the object so that the object is also decorated as a staticTen      One     //Calls are called with the class name, (there are only two ways to call the method: Object invocation and class name invocation, where no object can be called with the class name, so static) A      Public StaticSingle getinstance () { -         returns; -     } the}
 Public classSingledemo { Public Static voidMain (string[] args) {Singleton1 s=singleton1.getinstance ();    S.print (); }}/*design the class into a single case design pattern: A hungry man type*/classsingleton1{//privatization of constructor functions    PrivateSingleton1 () {}//defines and instantiates an object of this class    Private StaticSingleton1 s =NewSingleton1 ();  Public StaticSingleton1 getinstance () {returns; }         Public voidprint () {System.out.println ("A Hungry man style--single case design mode"); }}

If you want the class to be able to build only one object then simply add the three parts to the class (describe how this class should be described)

1  Public classSingleDemo1 {2      Public Static voidMain (string[] args) {3         //Test T1 = new test ();4         //Test t2 = new test ();5Test T1 =test.getinctance ();6Test t2 =test.getinctance ();7T1.setnum (10);8T2.setnum (20);9 System.out.println (T1.getnum ());TenSystem.out.println (T2.getnum ());//Two print results are 20 because there is only one object in memory One     } A } - classtest{ -     Private intnum; the     Private StaticTest T =NewTest (); -     PrivateTest () {} -      Public StaticTest getinctance () { -         returnT; +     } -      Public voidSetnum (intnum) { +          This. num =num; A     } at      Public intGetnum () { -         returnnum; -     } -}

Three, lazy type:

The object is initialized when the method is called, and is called the lazy load of the object.
Single class into memory, objects also BAA exist, only when the GetInstance method is called, the object is established

 Public classSingledemo { Public Static voidMain (string[] args) {Singleton2 s=singleton2.getinstance ();    S.print (); }}//Lazy Typeclasssingleton2{Private StaticSingleton2 s =NULL; PrivateSingleton2 () {} Public StaticSingleton2 getinstance () {if(s==NULL) {s=NewSingleton2 (); }        returns; }     Public voidprint () {System.out.println ("Lazy-type-single-case design mode"); }}

1  Public classSingleDemo2 {2      Public Static voidMain (string[] args) {3 4     }5 6 }7 classsingle{8     Private StaticSingle S =NULL;9     PrivateSingle () {}Ten     //synchronized (synchronous) as long as there is a program in the other programs can not come in, but the efficiency of the program is reduced, before the implementation of the need to judge One      Public Static synchronizedSingle getinstance () { A         //reduce the number of locks to be judged -         if(s==NULL){ -             //The Final Solution, reduce the number of judgments, the above function is not synchronized the             synchronized(Single.class){ -                 if(s==NULL) -s =NewSingle (); -             } +         } -         returns; +     } A}

Join synchronization in order to resolve multithreading security issues. double judgment is added to solve the problem of efficiency.

Java design mode _single (Singleton design 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.