设计模式(一)单例模式

单例模式是一种常用的软件设计模式,其定义是单例对象的类只能允许一个实例存在。书上都会提到 饿汉式 和 懒汉式 这两种方式。下面具体些一些实现的例子

1、饿汉式,使用静态变量的方式实现。不存在线程同步的问题。在类加载的过程中实例化。

public class Singleton {
    private final static Singleton INSTANCE = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

2、饿汉式,使用静态代码块的方式实现。和上面没有什么区别。

public class Singleton {
    private static Singleton instance;
    static {
        instance = new Singleton();
    }
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

3、懒汉式,存在线程安全问题,多线程的环境下不可使用。

public class Singleton {
    private static Singleton singleton;
    private Singleton() {}
    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

4、懒汉式,为解决上面函数存在线程不安全的问题,可以多getInstance()进行同步。

public class Singleton {
    private static Singleton singleton;
    private Singleton() {}
    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

5、懒汉式,同样是解决线程不安全的问题,除了对实例化的函数进行同步,还可以使用同步代码块进行双重检测

//优先考虑这种写法
public class Singleton {
    private static volatile Singleton singleton;
    private Singleton() {}
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

6、枚举类型实现单例模式。用enum实现Singleton时线程安全,保证单例。使用方法Singleton.INSTANCE.otherMethods();

//优先考虑这种写法
enum Singleton{
    INSTANCE;
    public void otherMethods(){
        System.out.println("Something");
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值