设计模式 - 单例模式

/**
 * 第一种(懒汉,线程不安全),缺点线程不安全
 */
class Singleton1 {
    private static Singleton1 singleton1;
    private Singleton1() {
    }
    public static Singleton1 getInstance() {
        if (singleton1 == null) {
            singleton1 = new Singleton1();
            return singleton1;
        } else {
            return singleton1;
        }
    }
}

/**
 * 第二种(懒汉,线程安全),缺点效率很低
 */
class Singleton2 {
    private static Singleton2 singleton2;
    private Singleton2() {
    }
    public static synchronized Singleton2 getInstance() {
        if (singleton2 == null) {
            singleton2 = new Singleton2();
            return singleton2;
        } else {
            return singleton2;
        }
    }
}

/**
 * 第三中(饿汉,线程安全),缺点不支持延迟加载,如果可以的话建议使用,不容易产生其他问题
 */
class Singleton3 {
    private static Singleton3 singleton3 = new Singleton3();
    private Singleton3() {
    }
    public static Singleton3 getInstance() {
        return singleton3;
    }
}

/**
 * 第四中(饿汉,变种),跟第三种类似,优点是在初始化类时可以添加其他操作
 */
class Singleton4 {
    private static Singleton4 singleton4;
    static {
        singleton4 = new Singleton4();
    }
    private Singleton4() {
    }
    public static Singleton4 getInstance() {
        return singleton4;
    }
}

/**
 * 第五中(静态内部类),跟第三种类似,优点是在初始化类时不会初始化静态类
 * 只有在调用时才进行初始化,在希望实现延迟加载时推荐使用该方法
 */
class Singleton5 {
    private static class Singleton5Holder {
        public static Singleton5 INSTANCE = new Singleton5();
    }
    private static Singleton5 singleton5;
    private Singleton5() {
    }
    private Singleton5 getInstance() {
        if (singleton5 == null) {
            singleton5 = Singleton5Holder.INSTANCE;
            return singleton5;
        } else {
            return singleton5;
        }
    }
}

/**
 * 第六中(枚举),推荐做法,不过很少见
 */
enum Singleton6 {
    INSTANCE;
    public void whateverMethod() {
    }
}

/**
 * 第七中(双重检查锁定),只有在java1.5以上的版本可以使用,推荐使用静态内部类来实现
 */
class Singleton7 {
    private volatile static Singleton7 singleton7;
    private Singleton7() {
    }
    public static Singleton7 getInstance() {
        if (singleton7 == null) {
            synchronized (Singleton7.class) {
                if (singleton7 == null) {
                    singleton7 = new Singleton7();
                }
                return singleton7;
            }
        } else {
            return singleton7;
        }
    }
}

/**
 * 单例模式还可以进行扩展,变为有上限的多例模式,具体方法可以类比静态类
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值