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);
}
}