设计模式:对问题行之有效的解决方式。其实它是一种思想。
1,单例设计模式。
解决的问题:就是可以保证一个类在内存中的对象唯一性。
必须对于多个程序使用同一个配置信息对象时,就需要保证该对象的唯一性。
如何保证对象唯一性呢?
1,不允许其他程序用new创建该类对象。
2,在该类创建一个本类实例。
3,对外提供一个方法让其他程序可以获取该对象。
步骤:
1,私有化该类构造函数。
2,通过new在本类中创建一个本类对象。
3,定义一个公有的方法,将创建的对象返回。
//饿汉式
class single//类一加载,对象就已经存在
{
private static single s = new single();
private single() { }
public static single getinstance()
{
return s;
}
}
//懒汉式
class single2//类加载进来,没有对象,只有调用了getinstance方法时,才会创建对象,延迟加载形式
{
private static single2 s = null;
private single2() {
}
public static single2 getinstance()
{
if (s == null)
s = new single2();
return s ;
}
}
class Test
{
private int num;
private static Test t = new Test();
private Test() {}
public static Test getinstance()
{
return t;
}
public void setnum (int num)
{
this.num = num;
}
public int getnum( )
{
return num;
}
static class singleDemo
{
public static void main (String[] args)
{
single s1 = single.getinstance();
single s2 = single.getinstance();
System.out.println(s1 == s2);
Test t1 = Test.getinstance();
Test t2 = Test.getinstance();
t1.setnum(10);
t2.setnum(90);
System.out.println(t1.getnum());
System.out.println(t2.getnum());
}
}
}