下面是 Java 的单例模式示例
- SingletonObject.java
public class SingletonObject {
// 单列对象属性
private final String name;
private final String location;
// 创建 SingletonObject 对象
private static final SingletonObject instance = new SingletonObject();
// 让构造函数为 private,这样该类就不会被实例化
private SingletonObject() {
name = "beijing university";
location = "beijing";
}
// 获取唯一可用的对象
public static SingletonObject getInstance() {
return instance;
}
// 获取单列对象属性
public void showMessage() {
System.out.println("name = " + name);
System.out.println("location = " + location);
}
}
- Main.java
public class Main {
public static void main(String[] args) {
// 编译时错误:构造函数 SingletonObject() 是不可见的
// SingletonObject object = new SingletonObject();
// 获取唯一可用的对象
SingletonObject object1 = SingletonObject.getInstance();
SingletonObject object2 = SingletonObject.getInstance();
// 显示消息
object1.showMessage();
object2.showMessage();
}
}
单例模式的Python实现请见