Java design pattern-Singleton mode

Source: Internet
Author: User

Problem Analysis:

First of all to clarify a problem, that is, in some cases, some objects, we need only one, for example, a computer can be connected to several printers, but this computer has only one printing program, here can be a singleton mode to avoid two print jobs simultaneously output to the printer, That is, I have only one instance of the print program throughout the printing process.
In short, a singleton pattern (also called a single-piece mode) is a guarantee that at any one time in the entire application lifecycle, instances of the Singleton class will only exist (or they may not exist ).

Definition of a singleton pattern:

Ensure that a class has and has only one instance , and instantiates itself and provides an entire instance to the entire system

Usage scenarios for a singleton pattern:

Make sure that a class has and only one object of the scene, to avoid producing more than one object that consumes too much resources, or that an object of an object type should have only one.

Key points for implementing the Singleton pattern:

1, the constructor is not open to the outside, generally private

2, returns a singleton class object through a static method or enumeration

3, ensure that the Singleton class has only one object, especially in a multithreaded environment

The singleton mode has the following characteristics:

1, the Singleton class can have only one instance .
2, the Singleton class must create its own unique instance .
3. The Singleton class must provide this instance to all other objects .

The simple point is:

First, the singleton pattern enables a class to have only one instance at any point in the program's life cycle.
Then, the Singleton constructor is private, and if the external program wants to access the Singleton class ,
An instance of this singleton class must be requested (note the request) through getinstance ().

Lazy mode:

public class Singleton  {private   Singleton () {};//Private constructor: makes external cannot use constructors to create the object   private static Singleton msingleton=null;//private static constants are not instantiated: private guarantees only internal access to the variable, static for the class public   static synchronized Singleton Getsingleton ( ) {//public static release: added a synchronous   if (msingleton=null)   {      Msingl eton=new Singleton ();   }   return Msingleton;}


What is a lazy single case, it can be understood that the singleton pattern, which exists in the entire application life cycle only one instance, lazy, that is the only instance of this singleton class is instantiated the first time with Getsingleton (), if you do not call Getsingleton (), this instance does not exist, that is, null. The image point says that you do not move it, it is not instantiated itself, so it can be called lazy

First the Singleton class creates an instance at the first call to Getsingleton () and encapsulates the instance's reference in its own class, and then calls Getsingleton () at a later time to determine if there is an instance of the Singleton. If present, the instance is no longer created. Instead, an instance of the previously generated class is called, so that there is only one instance in the entire application.

Advantage: It is instantiated only at the time of use,

Cons: Each call to Getsingleton () is synchronized, resulting in unnecessary synchronization overhead and is not recommended for use


A Hungry man mode:

public class Singleton  {private   Singleton () {};//Private constructor: Make external cannot use constructor to create the object   private static  final Singleton msingleton=new Singleton ();//private static constant and instantiation: private guarantees only internal access to the variable, static is related to the class, and final once initialized cannot modify public   static Singleton Getsingleton () {//public static Release method: Only this method can be used to get the static constant   return Msingleton;}

The above introduces the A Hungry man-type single case, to here to understand the lazy-type single case, it is easier, lazy type single case because people lazy, so its own is not active instantiation of the only instance of a single case, and a hungry man-style words, then just the opposite, because of the hungry, so everywhere to eat food, people have become active a lot, So there's no need for anyone else to push him. Instantiating a singleton class as an instance, the Singleton class is instantiated by itself.


Example: A company has only one CEO, can have a few VP, countless employees, but the CEO has only one

Staff.java

public class staff{public  Void Works () {  //work}}

Vp.java

public class VP extends staff {  @Override public   void work () {  //Manage Employees    }}

Ceo.java

Package Com.hust.singleton;//ceo Singleton mode (a Hungry man mode) public class CEO extends staff{Private CEO () {};//Private constructor: Make external cannot use constructor to create the object Private static final CEO Mceo=new CEO ();//privacy constant and instantiation: private guarantees only internal access to the variable, static is related to the class, and final once initialized cannot modify public static CEO G      Etceo () {//public static Release method: Only this method can be used to get the static constant return MCEO;} @Override public void Work () {//admin VP}}/*1. A hungry man mode * public class Singleton {private Singleton () {};//Private constructor: makes the external not Use the constructor to create the object private static final Singleton msingleton=new Singleton ();//private statically constant and instantiated: private guarantees only internal access to the variable, static is related to the class, Final once initialized, you cannot modify public static Singleton Getsingleton () {//publicly-statically: This method can only be used to obtain a static constant return Msingleton;} * 2, lazy mode, advantages: Every time only when using Is instantiated, the disadvantage: every call Getsingleton () to listen to, resulting in unnecessary synchronization overhead, is not recommended to use the * public class Singleton {private Singleton () {};//Private constructor: Make external cannot use constructs function to create the object private static Singleton msingleton=null;//private statically constant is not instantiated: private guarantees only internal access to the variable, static for the class public static Synchroni Zed Singleton Getsingleton () {//public static release method: Added a synchronous if (msingleton=null) {Msingl eton=new Singleton(); } return Msingleton;} *  *  *  */

Company.java

Package Com.hust.singleton;import Java.util.arraylist;import Java.util.list;public class Company {     private List <Staff> mallstaffs=new arraylist<staff> ();     public void Addstaff (mstaff) {     mallstaffs.add (mstaff);}     public void Showallstaffs () {for (staff mstaff:mallstaffs) {System.out.println ("OBJ:" +mstaff.tostring ())}}}

Test.java

Package Com.hust.singleton;import Java.security.publickey;public class Testsingleton {/** * @param args */public static V OID Main (string[] args) {company  mcompany=new Company ();  The CEO object can only get the staff  Mceo1=ceo.getceo () through the GETCEO function;  Staff Mceo2=ceo.getceo ();  Mcompany.addstaff (MCEO1);  Mcompany.addstaff (MCEO2);  Create VP object through new staff    mvp1=new VP ();  Staff mvp2=new VP ();  Mcompany.addstaff (mVP1);  Mcompany.addstaff (mVP2);  Create staff objects through new staff  mstaff1=new staff ();  Staff mstaff2=new staff ();  Staff mstaff3=new staff ();  Mcompany.addstaff (MSTAFF1);  Mcompany.addstaff (MSTAFF2);  Mcompany.addstaff (MSTAFF3);    Mcompany.showallstaffs (); }}

Output Result:

Obj:[email Protected]obj:[email protected]//Only one instance Obj:[email protected]obj:[email Protected]obj:[email protected] Obj:[email Protected]obj:[email protected]


Java design pattern-Singleton mode

Related Article

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.