Loading

单例设计模式

单例设计模式要保证内存中只存在一个对象,有饿汉式和懒汉式两种,懒汉式也成为单例延迟加载模式。

饿汉式

class Singleton {
    // 1、私有构造方法,其他类不能访问构造方法
    private Singleton(){}
    // 2、创建本类对象
    private static Singleton s = new Singleton();

    public static Singleton getInstant(){
        return s;
    }

}

懒汉式

class Singleton {
    // 1、私有构造方法,其他类不能访问构造方法
    private Singleton(){}
    // 2、声明一个引用
    private static Singleton s;

    public static Singleton getInstant(){
        if(s == null){
            s = new Singleton();
        }
        return s;
    }
}

区别

1、饿汉式是空间换时间,懒汉式是时间换空间;
2、在多线程访问时,饿汉式不会创建多个对象,懒汉式可能会创建多个对象。

posted @ 2017-02-27 16:58  leon_x  阅读(24)  评论(0)    收藏  举报