单例设计模式的要求:
1在某些情况下为了避免死其他程序过多的该类的对象,则需禁止其他程序建立该类的对象.
2但是又需要让其他程序能够访问到该类的对象,只好在本类中自定义一个对象
3这个自定义对象要被其他程序访问,就必须在该类中对外提供一些访问方式
由以上要求,单例模式的设计思路:
1将构造器函数私有化,这样就可以避免其他程序创建该类的对象.
2在该类中创建一个本来对象
3提供一个方法以便获取该对象---因为外界程序无法创建该类对象,所以调用该方法只能通过类名调用的形式来调用方法,所以该方法必须为static修饰的,要被外界访问,所以为public修饰权限
package cn.imust.day;
//单例设计模式
class SingleInstance
{
private int num;
public void setNum(int num){
this.num=num;
}
public int getNum(){
return this.num;
}
//the above Javabean is order to test this Class can only have one instance
//the private constructor
private SingleInstance(){}
//the user-defined instance
private static SingleInstance single =new SingleInstance();
//the method offer to other programs
public static SingleInstance getInstance(){
return single;
}
}
//definite a class to test the Singleton pattern
class TestSingle
{
public static void main(String[] args){
SingleInstance single1=SingleInstance.getInstance();
SingleInstance single2=SingleInstance.getInstance();
single1.setNum(23);
System.out.println(single2.getNum());//the finally output is 23,indicate that the instance is the same one
}
}
具体in using ,we create the class like usually we do ,but when we need the class only have one instance ,just add the three conditions .
There are two methods for creating of Singleton pattern ,the above is one,which called "饿汉式单例设计模式" ,the other is called "懒汉单例设计模式",the key point is also the difference ,look at :
private static SingleInstance single=null;
//the method offer to other programs
public static SingleInstance getInstance(){
if (single==null)
{
single=new SingleInstacne();
}
return single;
}
多线程中的懒汉式单例:
class Single
{
private static Single s=null;
private Single(){}
public static Single getInstance(){//there you may not use the 同步函数,becuase if so,you need to check the 锁棋标志 many times,witch will decline the efficiency,so use the 同步代码块 like below:
if (s==null)
{
synchronized(Single.class){
if (s==null)
{
s=new Single();
}
}
}
return s;
}
}