GOF设计模式——单例模式

本文介绍了Java中的两种单例模式实现:饿汉式和懒汉式。饿汉式在类加载时即创建单例对象,确保线程安全但牺牲了延迟初始化的优点。懒汉式则在首次调用时才创建对象,实现了延迟初始化,但在多线程环境下可能存在线程安全问题。测试代码展示了两种方式的使用。
摘要由CSDN通过智能技术生成

单例模式

/**
 * 饿汉式
 */
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());

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值