单件模式
用来创建独一无二的,只能有一个实例的对象的入场券。
确保类只有一个实例,并提供一个全局访问点
单件
/**
* 构造器私有
* 确保类只有一个实例,并提供一个全局访问点
*
* @author NNroc
* @date 2020/8/12 14:22
*/
public class Singleton {
// 在静态除初始器中创建单件,保证线程安全
private static Singleton uniqueInstance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
// 有实例既可直接使用
// if (uniqueInstance == null) {
// uniqueInstance = new Singleton();
// }
return uniqueInstance;
}
}
/**
* @author NNroc
* @date 2020/8/12 14:42
*/
public class Singleton2 {
// 当 uniqueInstance 变量被出身寒微 Singleton2 实例时,多个线程正确处理它
// 这个方法打打减少 getInstance() 的时间消耗,优化性能
private volatile static Singleton2 uniqueInstance;
private Singleton2() {
}
public static Singleton2 getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton2.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton2();
}
}
}
return uniqueInstance;
}
}
巧克力工厂示例
/**
* @author NNroc
* @date 2020/8/12 14:31
*/
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
private static ChocolateBoiler chocolateBoiler;
private ChocolateBoiler() {
empty = true;
boiled = false;
}
public static ChocolateBoiler getInstance() {
if (chocolateBoiler == null) {
chocolateBoiler = new ChocolateBoiler();
}
return chocolateBoiler;
}
public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// 填充巧克力和牛奶的混合物
}
}
public void drain() {
if (!isEmpty() && isBoiled()) {
// 排出煮沸的巧克力和牛奶的混合物
empty = true;
}
}
public void boil() {
if (!isEmpty() && !isBoiled()) {
// 煮沸
boiled = true;
}
}
public boolean isEmpty() {
return empty;
}
public boolean isBoiled() {
return boiled;
}
}