Java design patterns :( B) Singleton

Java design patterns: Singleton

Defined singleton (the Singleton) mode: refers to only one instance of a class, and the class to create a model of the instance itself.

Intent: to ensure that only one instance of a class, and provide a global access point to access it.

Mainly to solve: a global classes used to create and destroy frequently.

Singleton pattern implemented steps of:

1. only one instance of a class

If you want to do only one instance so that the constructor can not be public, it is private. Since the constructor of the class if it is public, it can be by way of new SingleObject () to create an instance, can not guarantee that only one instance

Example 2. Generate

Constructor is private, then only be able to access the class constructor SingleObject class, you can only call the constructor method to generate its own instance in the SingleObject

 private SingleObject instance = new SingleObject();

3. Global is only one access point

If the above statement has been generated instance instance, but the instance is private, and only members of the class can access SingleObject, this is not consistent, then it is a new method to return the instance getInstance (). Another point does not conform: Each call method will be back in one instance, this is not consistent, then a new method for the static keyword, so that he can only produce an object.

   public static SingleObject getInstance(){
      return instance;
   }

 

4. Static methods can only access static member variables

Then add the static keyword as a member variable

private static SingleObject instance = new SingleObject();
Here is the code of singleton
public class SingleObject {

   // static methods can only access static member variables 
   Private  static SingleObject instance = new new SingleObject ();

   // Why constructor is private, because if it is public so that an object for each new generation will have an object, does not meet the Singleton pattern. It can not be used SingleObject instance = new SingleObject ();  

   private SingleObject(){}

   // then use Reflection classes. Invoke a method name of ways to generate the object in a static method. You can not call every method to produce an object, then it generates an object in the class, and returns it to the object. 
   public  static SingleObject the getInstance () {
       return instance;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}

 

Guess you like

Origin www.cnblogs.com/eathertan/p/12532179.html