Java design pattern Simple interest mode

Source: Internet
Author: User

Simple interest Mode: ensures that a class has at most one instance and provides a global access point .

Classic simple interest mode creating object code

 public  class   Singleton { static  Singleton uniqueinstance = ;  private   Singleton () {}  
   
    public  
    static  
     Singleton getinstance () {  
    if  (Uniqueinstance==
    null  
     =new   Singleton ();     return   uniqueinstance; }}
   

Problem: Multithreading

 Public classQ {//Multithreading    Private StaticQ uniqueinstance =NULL; PrivateQ () {} Public StaticQ getinstance () {if(uniqueinstance==NULL) {//when thread 1 executes this statement, it is judged through,            /*when preparing to execute Uniqueinstance=new Q (), thread 2 preempted to the CPU resource, * switch to thread 2 to start execution, thread 2 will find uniqueinstance or null, so the object is created, after creation,             * And when switching to thread 1 o'clock, found that thread 1 has entered the if judgment, so will also create a new uniqueinstance, * at this time thread 1 created uniqueinstance and thread 2 created Uniqueinstanc is not the same **/uniqueinstance=NewQ (); }        returnuniqueinstance; }}

Solutions

1. Methods for creating objects and synchronizing locks

/*** Optimization Mode 1 * method to add a sync lock * Advantages: Easy to use * disadvantage: When the thread is a lot of cases, very resource-intensive *@authorYXM **/ Public classoptimization_singleton_1 {Private StaticOptimization_singleton_1 uniqueinstance =NULL; Privateoptimization_singleton_1 () {} Public synchronized Staticoptimization_singleton_1 getinstance () {if(uniqueinstance==NULL) {uniqueinstance=Newoptimization_singleton_1 (); }        returnuniqueinstance; }}

2. A hungry man-style object creation

/*** Optimization Mode 2 * Eager to create objects * Advantages: No resource consumption due to lock-up * Disadvantage: memory is still consumed when not using this class *@authorYXM **/ Public classoptimization_singleton_2 {Private StaticOptimization_singleton_2 uniqueinstance =Newoptimization_singleton_2 (); Privateoptimization_singleton_2 () {} Public Staticoptimization_singleton_2 getinstance () {if(uniqueinstance==NULL) {uniqueinstance=Newoptimization_singleton_2 (); }        returnuniqueinstance; }}

3, double check locking (More perfect)

/*** Optimization Mode 3 * Double check plus lock * More Perfect *@authorYXM **/ Public classOptimization_singleton_3 {Private volatile StaticOptimization_singleton_3 uniqueinstance =NULL;//volatile is used by the compiler to ensure thread safety    Privateoptimization_singleton_3 () {} Public synchronized Staticoptimization_singleton_3 getinstance () {if(uniqueinstance==NULL) {
Only wait for thread 1 to create the object, other threads will enter the following code block
synchronized(Optimization_singleton_3.class){ if(uniqueinstance==NULL) {uniqueinstance=Newoptimization_singleton_3 (); } } } returnuniqueinstance; }}

Case: A chocolate factory, producing a variety of chocolates, the production process has (prepare raw materials, filling, heating, discharge) four processes, but now there is only one production line in the factory, which means that only one chocolate can be produced at a time, how to control?

Analysis: Converting to computer thinking, this scenario is typical for a class that can have only one object that conforms to the simple interest pattern feature

Ordinary Chocolate Factory

 Public classChocolatefactory {Private Booleanempty; Private Booleanboiled;  Publicchocolatefactory () {Empty=true; Boiled=false; }    //Fill     Public voidFill () {if(empty) {empty=false; Boiled=false; }    }    //Heating     Public voidBoil () {if(!boiled) {Boiled=true; }    }    //Discharge     Public voidDrain () {if(!empty&&boiled) {Empty=true; }    }}

Chocolate Factory with simple interest mode

 Public classChocolatefactoryinsingleton {Private Booleanempty; Private Booleanboiled;  Public StaticChocolatefactoryinsingleton uniqueinstance=NULL; PrivateChocolatefactoryinsingleton () {Empty=true; Boiled=false; }     Public StaticChocolatefactoryinsingleton getinstance () {
Here to ensure that different chocolates do not enter the same line
if(uniqueinstance==NULL) {uniqueinstance=NewChocolatefactoryinsingleton (); } returnuniqueinstance; } //Fill Public voidFill () {if(empty) {empty=false; Boiled=false; } } //Heating Public voidBoil () {if(!boiled) {Boiled=true; } } //Discharge Public voidDrain () {if(!empty&&boiled) {Empty=true; } }}

Java design pattern Simple interest 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.