I am learning design mode, the following is the simplest single example, the so-called single example is a single instance, is that a class can only generate one object. A single example pattern can be divided into three steps. The code is as follows:
public class Singleton
{
private Singleton ()
{
}
private static Singleton singleton=new Singleton ();
Static Singleton Getsingleton (Singleton instance)
{return
instance;
}
}The first function is a refactoring of the Singleton class construction method, which is declared private in order not to allow other classes to go directly to the new one singleton (), and the refactoring of the method is independent of the return value. Since an external class cannot generate a singleton class object, the Singleton object can only be declared inside itself, and then a reference to that type object is returned through a function.
Having identified this idea, the next step is to generate an object that, in order not to allow the external class to be referenced, is also declared private permission.
In the third step, you should declare a function that returns a reference to the Singleton class object generated in the second step. In general, however, the outer class wants to invoke the Getsingleton method by invoking a reference to the Singleton class object, because we are implementing a singleton pattern, and an instance has been generated in the second step. This is not workable. All Getsingleton methods are declared static so that the outer class can invoke the method directly through the form Singleton.getsingleton (Singleton instance). Well, write here and add static in the second step, because non-static member variables cannot be referenced in the static method.