定义:单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。
结构图:
public class Singleton {
public static Singleton s;
public static Singleton GetInstance(){
if (s == null) {
s = new Singleton();
}
return s;
}
}
public class Client {
public static void main(String[] args) {
Singleton s1 = new Singleton();
Singleton s2 = new Singleton();
if (s1 == s2) {
System.out.println("same");
}
else {
System.out.println("not the same");
}
}
}