【设计模式】单件模式

单件模式算是一个较为容易的设计模式,但也是重要的设计模式,需要掌握。

概述

单件模式确保一个类只有一个实例,并提供一个全局访问点。

单线程代码(懒汉式,线程不安全)

class Single {
     
    private static Single instance;

    private Single() {
     
        System.out.println("我被创建了");
    }
    public static Single getInstance() {
     
        if (instance == null) {
     
            instance = new Single();
        }
        return instance;
    }

    public static void main(String[] args) {
     
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        // 输出:
        // 我被创建了
    }
}

多线程代码(懒汉式,线程安全)

class Single {
     
    private static Single instance;

    private Single() {
     
        System.out.println("我被创建了");
    }
    public static synchronized Single getInstance() {
     
        if (instance == null) {
     
            instance = new Single();
        }
        return instance;
    }

    public static void main(String[] args) {
     
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        // 输出:
        // 我被创建了
    }
}

饿汉式

class Single {
     
    private static Single instance = new Single();

    private Single() {
     
        System.out.println("我被创建了");
    }
    public static synchronized Single getInstance() {
     
        return instance;
    }

    public static void main(String[] args) {
     
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        // 输出:
        // 我被创建了
    }
}

双重检验锁DCL(防止同步带来的低效率)

class Single {
     
    private static volatile Single instance;

    private Single() {
     
        System.out.println("我被创建了");
    }
    public static Single getInstance() {
     
        synchronized (Single.class) {
     
            if (instance == null) {
     
                instance = new Single();
            }
        }
        return instance;
    }

    public static void main(String[] args) {
     
        Single s1 = Single.getInstance();
        Single s2 = Single.getInstance();
        // 输出:
        // 我被创建了
    }
}

你可能感兴趣的:(设计模式)