/**
Design pattern: GOF (Gang of Four) book: design mode
Singleton design pattern: Resolves a class that only has one object in memory.
*/
/**
A hungry man singleton mode: Initializes an object first. Commonly used in development.
*/
Class single{
private String name;
private int age;
Private single () {}; These three steps ensure that the class has only one object in memory.
private static Single S = new single ();
public static single getinstance () {//Developer but use getinstance method on Demand
return s;
}
public void Setage (int.) {
This.age = age;
}
public int getage () {
return age;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
}
/**
Lazy Singleton mode: An object is initialized when the program calls the method.
*/
Class single1{
private String name;
private int age;
Private Single1 () {}; These three steps ensure that the class has only one object in memory.
private static Single1 s = new Single1 ();
The difference between the public static Single1 getinstance () {//A hungry man type and the lazy type is here.
if (s = = null) {
Synchronized (Single1.class) {//prevents the program from running into a deadlock state.
if (s = = null)
s = new Single1 ();
}
}
return s;
}
public void Setage (int.) {
This.age = age;
}
public int getage () {
return age;
}
public void SetName (String name) {
THIS.name = name;
}
Public String GetName () {
return name;
}
}
Class singledemos{
public static void Main (String args[]) {
Single1 S1 = single1.getinstance ();
Single1 s2 = single1.getinstance ();
S1.setname ("Lzl");
System.out.println (S2.getname ());
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A single-instance pattern of Java design patterns