大话设计模式——单例模式

来源:互联网 发布:aamtool mac 下载 编辑:程序博客网 时间:2024/05/17 08:25

前言

有些对象,只需要一个就足够了,比如线程池、日志文件,这时我们就需要用到单例模式。

饿汉模式

创建类的时候,就已经有了实例了,比较早些的创建,为饿汉模式

public class Test {    public static void main(String[] args) {        Singleton s1 = Singleton.getInstance();        Singleton s2 = Singleton.getInstance();        if (s1 == s2) {            System.out.println("s1==s2");        } else {            System.out.println("s1!=s2");        }    }}class Singleton{    //1.私有化构造方法,不允许外部直接创建对象    private Singleton() {    }    //2.创建类的唯一实例    private static Singleton instance = new Singleton();    //3.提供一个用于获取实例的方法    public static Singleton getInstance() {        return instance;    }}

二、懒汉模式

public class Test {    public static void main(String[] args) {        Singleton2 s1 = Singleton2.getInstance();        Singleton2 s2 = Singleton2.getInstance();        if (s1 == s2) {            System.out.println("s1==s2");        } else {            System.out.println("s1!=s2");        }    }}class Singleton2{    //1.私有化构造方法,不允许外部直接创建对象    private Singleton2(){    }    //2.声明类的唯一实例    private static Singleton2 instance;    //3.提供一个用于获取实例的方法    public static Singleton2 getInstance() {        if (instance == null) {            instance = new Singleton2();        }        return instance;    }}

三、对比

饿汉模式是加载类是比较慢,运行时比较快,线程安全
懒汉模式是加载类是比较快,运行时比较慢,线程不安全

原创粉丝点击