/*
单例设计模式保证变量的唯一性
*/
//饿汉式单例设计模式
class SingleDemo
{
private int num;
public void setNum(int num)
{
this.num = num;
}
public int getNum()
{
return num;
}
private SingleDemo(){}
private static SingleDemo s = new SingleDemo();
public static SingleDemo getInstance()
{
return s;
}
}
class SingleTest
{
public static void main(String[] args)
{
//SingleDemo s1 = SingleDemo.getInstance();
//SingleDemo s2 = SingleDemo.getInstance();
Single s1 = Single.getInstance();
Single s2 = Single.getInstance();
s1.setLen(30);
int sun = s2.getLen();
System.out.println("num="+sun);
}
}
//懒汉式单例设计模式
class Single
{
private int len;
public void setLen(int len)
{
this.len = len;
}
public int getLen()
{
return len;
}
private static Single sin = null;
public static Single getInstance()
{
if(sin==null)
{
synchronized(Single.class)
{
if(sin==null)
{
sin = new Single();
}
}
}
return sin;
}
}
|
|