Java code
// Static methods and static members can be called by all objects.
// Is the referenced Variable Also a member variable?
/*
Requirements:
Define a class to ensure that the class only has one object in the memory.
Ideas:
1. Do not allow other classes to create such objects.
2. Define a class object.
3. Provide the custom object.
Design Mode: it is an effective solution to a certain type of problems.
Singleton design mode: Ensure the uniqueness of the class objects in the memory.
Steps:
1. Define private and static objects of this class.
2. private constructor.
3. Provide a static method to return this object.
*/
Class Single
{
Private static/* final */Single s = new Single ();
Private Single (){}
Public static Single getSingle ()
{
Return s;
}
}
Class Single2
{
Private static Single2 s = null;
Private Single2 (){}
Public static/* synchronized */Single2 getSingle2 ()
{
If (s = null)
S = new Single2 ();
Return s;
}
}
Class SingleDemo
{
Public static void main (String [] args)
{
Single s1 = Single. getSingle ();
Single s2 = Single. getSingle ();
S1.setAge (10 );
S2.setAge (30 );
System. out. println (s1.getAge ());
System. out. println (s2.getAge ());
}
}