设计模式【四】单例模式

单例模式:一个类只能创建一个实例。

类图:

实现方式有以下几种:

1、懒汉式:

 public class Export {

    private static Export export;

    private Export() {
    }

    public static Export getInstance() {
        if (export == null) {
            export = new Export();
        }
        return export;
    }

    public void print(){
        System.out.println("this is singleton");
    }

}

2、线程安全懒汉式:全部实例加锁

 public class SyncFuncExport {

    private static SyncFuncExport export;

    private SyncFuncExport() {
    }

    public static synchronized SyncFuncExport getInstance() {
        if (export == null) {
            export = new SyncFuncExport();
        }
        return export;
    }

    public void print(){
        System.out.println("this is synchronized function singleton");
    }

}

3、线程安全锁懒汉式:如果已初始化则没有锁,提高性能

 public class SyncClassExport {

    private static SyncClassExport export;

    private SyncClassExport() {
    }

    public static SyncClassExport getInstance() {
        if (export == null) {

            synchronized (SyncClassExport.class) {
                if (export == null) {
                    export = new SyncClassExport();
                }
            }

        }
        return export;
    }

    public void print(){
        System.out.println("this is synchronized class singleton");
    }

}

4、类加载时实例化,实现简单。

 public class InitExport {

    private static InitExport export = new InitExport();

    private InitExport() {
    }

    public static InitExport getInstance() {
        return export;
    }

    public void print(){
        System.out.println("this is init singleton");
    }

}

5、通过内部类,在使用时实例化

 public class InnerClassExport {

    private static class InnerClassExportInstance{

        public static final InnerClassExport export = new InnerClassExport();

    }

    private InnerClassExport() {
    }

    public static InnerClassExport getInstance() {
        return InnerClassExportInstance.export;
    }

    public void print(){
        System.out.println("this is inner class singleton");
    }

}

6、为避免子类实例化,添加final,不能被继承

 public final class InitExport {

    private static InitExport export = new InitExport();

    private InitExport() {
    }

    public static InitExport getInstance() {
        return export;
    }

    public void print(){
        System.out.println("this is init singleton");
    }

}

   转载规则


《设计模式【四】单例模式》 Euler 采用 知识共享署名 4.0 国际许可协议 进行许可。
  目录