单例函数设计模式

public class Singleton{

  String name="In my heart,you are the world";

  private static Singleton st=new  Singleton();//饿汗模式

  private Singleton(){  

  }

  public static Singleton  GetSingleton(){

  return st;

  }

}

public class Singleton2 {
//    单例  这个类 永远只有一个 实例
    String name ="In my heart,you are the world";
//    2在自己的类中 创建自己类型的对象 private static
    private static Singleton2 s ;
//    1 构造函数私有的
    private Singleton2() {}
//    3 定义public static  getter
    public static  Singleton2 getSingleton() {
        if(s == null) {
            s =  new Singleton2();//懒汉模式
        }
        return s;
    }
}

public class TestSingleton {

    public static void main(String[] args) {
        Singleton x = Singleton.getSingleton();
        Singleton x1 = Singleton.getSingleton();
        Singleton x2 = Singleton.getSingleton();
        System.out.println(x.name);
        System.out.println(x1);
        System.out.println(x2);
    }
}

posted @ 2018-08-05 21:21  悄悄地超越  阅读(302)  评论(0编辑  收藏  举报