您的位置:首页 > 编程语言 > Java开发

Singleton 设计模式

2016-08-29 23:23 369 查看
懒汉式

public class Singleton {

    private static Singleton uniqueInstance = null;

 

    private Singleton() {

       // Exists only to defeat instantiation.

    }

 

    public static Singleton getInstance() {

       if (uniqueInstance == null) {

           uniqueInstance = new Singleton();

       }

       return uniqueInstance;

    }

    // Other methods...

}

饿汉式

class Single{

  private static Single onlyone = new Single();

  private String name;
public static Single getSingle() {

             r
eturn onlyone;

            }

            private Single() {}

  }

public class TestSingle{
public static void main(String args[]) {
Single  s1 = Single.getSingle();
Single  s2 = Single.getSingle();
if (s1==s2){
          System.out.println("s1 is equals to s2!");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式 java