2018-12-04

单例模式 



目录 

-饿汉模式

-懒汉模式

- 双重检测

- 静态内部类

- 枚举实现

- 容器实现



饿汉模式 

代码

public class Singleton1 {

    //线程安全,因为类创建的时候就创建一个静态的对象

    private static Singleton1 instance=new Singleton1();//保证线程安全

    private Singleton1() {}

    public static Singleton1 getInstance() {

        if(instance==null) {

            instance=new Singleton1();

        }

        return instance;

    }

}


懒汉模式 

代码

public class Singleton2 {

    //线程不安全的原因,没有创建初始化对象

    private static Singleton2 instance;//线程不安全

    private Singleton2() {}

    //使其线程安全的方法

    public synchronized static Singleton2 getInstance() {

        if(instance==null) {

            instance=new Singleton2();

        }

        return instance;

    }

}


双重检测(DCL) 

代码

public class Singleton3 {

    private static Singleton3 instance;

    private Singleton3() {}

    public static Singleton3 getInstance() {

        if(instance==null) {

            synchronized(Singleton3.class) {//线程安全

                if(instance==null) {

                    instance=new Singleton3();

                }

            }

        }

        return instance;

    }

}


静态内部类 

代码

public class Singleton4 {

    private Singleton4() {}

    public Singleton4 getInstance() {

        return SingletonHolder.SINGLETON;

    }

    private static class SingletonHolder{

        private static final Singleton4 SINGLETON=new Singleton4();

    }

}


枚举实现 

代码

public class Singleton5 {

    public enum SingletonEnum{

        INSTANCE;

    }

}


容器实现 

代码

import java.util.*;

public class Singleton6 {

     public static Map objMap=new HashMap();

     private Singleton6() {}

    //输入

    public static void registerInstance(String key,Object instance) {

        if(!objMap.containsKey(key))

            objMap.put(key, instance);

    }

    //输出

    public static Object getInstance(String key) {

        return objMap.get(key);

    }

}

你可能感兴趣的:(2018-12-04)