单例模式
/**
* 饿汉式
*/
public class HungryType {
private HungryType() {
quantity++;
}
private static int quantity=0;
//直接初始化穿件对象
private static HungryType hungryType = new HungryType();
public static HungryType getInitialize() {
return hungryType;
}
public int myMethod() {
return quantity;
}
}
/**
* 懒汉式
*/
public class LazySingleton {
private static int quantity = 0;
private LazySingleton() {
quantity++;
}
private static LazySingleton lazySingleton = null;
//懒汉式是线程不安全的
public static synchronized LazySingleton getInstance() {
if (lazySingleton == null) {
synchronized (LazySingleton.class) {
lazySingleton = new LazySingleton();
}
}
return lazySingleton;
}
public int myMethod() {
return quantity;
}
}
测试单列模式
public class TextSingleton {
public static void main(String[] args) {
//饿函数
HungryType initialize = HungryType.getInitialize();
System.out.println(initialize.myMethod());
//饿汉式
LazySingleton instance = LazySingleton.getInstance();
System.out.println(instance.myMethod());
}
}