Java 设计模式:单例模式
在某些特殊场合中,一个类对外提供一个对象且只能是一个对象,这样的类叫做单例类,编写单例类的设计思想叫做单例设计模式。
代码示例
自定义 Singleton 类,实现该类的封装;自定义 TestSingleton 类,在 main 方法中能得到且只能得到 Singleton 类中的一个对象。
public class Singleton {
// 2. 提供本类的引用作为本类的成员变量 private static 表示提升为类的层次
private static Singleton sin = new Singleton();
// 饿汉式
// private static Singleton sin = null; // 懒汉式
// 1. 自定义无参的构造方法,使用 private 关键字修饰
// static 关键字不能修饰构造方法,加上 static 隶属于类层级,就不能访问非静态的成员了
private /*static*/ Singleton() { }
// 3. 提供公有的 get 成员变量方法将成员变量返回出去
public static Singleton getInstance() {
return sin;
// if(sin == null){ // 懒汉式 返回时才创建
// sin = new Singleton();
// }
// return sin;
}
}
public class TestSingleton {
public static void main(String[] args) {
// Singleton s1 = new Singleton();
// Singleton s2 = new Singleton();
// System.out.println(s1 == s2); // false 得到 Singleton 类中的两个对象
// 因为每次 new 等于重新开辟内存空间
Singleton.getInstance();
Singleton.getInstance();
System.out.println(s1 == s2);
}
}

