Single State mode:
To prevent a class of a single state pattern from being instantiated multiple times, you should set the constructor of the class to private, which guarantees that the class instance can only be obtained through a static method. And the static method guarantees
Each returned instance is the same, so that an instance of the class needs to be set as a class property, which can be set to static because it needs to be accessed by a static method
Property. Instances of a single State class are the same shared instance.
The sample code for a single state pattern is as follows:
public class Singletontest
{
int value;
private static Singletontest instance;
Private Singletontest ()
{
SYSTEM.OUT.PRINTLN ("Executing builder ...");
}
public static Singletontest getinstance ()
{
if (instance = null)
{
Instance = new Singletontest ();
}
return instance;
}
public int GetValue ()
{
return value;
}
public void SetValue (int value)
{
This.value = value;
}
public static void Main (string[] args)
{
singletontest T1 = singletontest.getinstance ();
Singletontest t2 = singletontest.getinstance ();
T2.setvalue (9);
System.out.println (T1==T2);
}
}