设计模式 单例模式

时间:2021-10-02 20:33:41

public class Singleton {

private static Singleton instance;
private Singleton()
{

}

public static Singleton GetInstance()
{
if(instance == null)
{
instance = new Singleton();
}
return instance;
}
}

public class Program {

public static void main(String[] args) {
// TODO Auto-generated method stub
Singleton s1=Singleton.GetInstance();
Singleton s2=Singleton.GetInstance();

if(s1==s2)
{
System.out.println("两个对象是相同的实例");
}
else
{
System.out.println("两个对象是不同实例");
}
}

}