设计模式之单例、多例模式

单例

饱汉模式

public class Singleton {
    private static Singleton instance = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return instance;
    }
}

饥汉模式

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

枚举

public enum Singleton {
    INSTANCE();
    
    private Singleton() {}
    
    public void method() {
        // do something
    }
}

 

多例

public class Multiton {
    private static Multiton instance1 = new Multiton();
    private static Multiton instance2 = new Multiton();
    
    private Multiton() {}
    
    public static Multiton getInstance(int key) {
       if(key == 1) {
           return instance1;
       } else {
           return instance2;
       }
    }
}
posted @ 2015-09-28 00:30  踮起脚尖眺望  阅读(137)  评论(0编辑  收藏  举报