设计模式--单例

2018-11-07  本文已影响0人  意大利大炮

简单介绍:

定义:

特点:

实现方式:

饿汉模式

代码如下:

public class Singleton2 {
    private static Singleton2 singleton2= new Singleton2();
    private Singleton2(){}
    public static Singleton2 getInstance() {
        return singleton2;
    }
    public static String getStr() {
        return "Create String type Object";
    }
}

懒汉模式

代码如下:

public class Singleton3 {
    private static Singleton3 singleton2 = null;
    private Singleton3();
    Tools.println("类实例化");
    }
    public static synchronized Singleton3 getInstance(){
        if(singleton2 == null)
            singleton2 = new Singleton3();
        return singleton2;
    }
    public static void CreateString(){
        Tools.print("Create String in Singleton3");
    }
}

双重检测方式

代码如下:

class Singleton1 {
    private Singleton1() {
    }
    public static Singleton1 instance = null;
    public static Singleton1 getInstance() {
        if (instance == null) {
            synchronized (Singleton1.class) {
                if (instance == null) {
                    instance = new Singleton1();
                }
            }
        }
        return instance;
    }
}

静态内部类实现

public class Singleton4 {
    private Singleton4(){}
    static class SingletonHolder {
    private static Singleton4 singleton = new Singleton4();
    }
    public static Singleton4 getInstance(){
    return SingletonHolder.singleton;
    }
}
public class Singleton4 {
    private Singleton4(){}
    static class SingletonHolder {
        private static Singleton4 singleton = new Singleton4();
    }
    public static Singleton4 getInstance(){
        return SingletonHolder.singleton;
    }
}

问题

private static Class getClass(String classname)  throws ClassNotFoundException {     
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader();     
      if(classLoader == null)     
         classLoader = Singleton.class.getClassLoader();     
     return (classLoader.loadClass(classname));     
   }     
}
public class Singleton implements java.io.Serializable {     
   public static Singleton INSTANCE = new Singleton();     
   protected Singleton() {     
   }     
   private Object readResolve() {     
            return INSTANCE;     
     }    
}   

应用场景:

总结以上,不难看出:

上一篇 下一篇

猜你喜欢

热点阅读