Java 设计模式(单件模式)

单件模式

用来创建独一无二的,只能有一个实例的对象的入场券。
确保类只有一个实例,并提供一个全局访问点

单件
/**
 * 构造器私有
 * 确保类只有一个实例,并提供一个全局访问点 
 *
 * @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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值