单例模式最初的定义出自《设计模式》:“保证一个类仅有一个实例,并提供一个访问它的全局访问点。”单例模式是一种常用的软件设计模式,它的核心在于包含被称为单例类的特殊类,此模式保证整个系统中,一个类仅有一个实例,且该实例提供给外界访问使用,从而方便对实例个数的控制和系统资源的节约。
在java中的理解,其实是一个类仅有一个实例,使用static修饰,自行实例化之后向整个系统提供这个实例,如下:
public class SingletonTest {
public String str=null;
private static SingletonTest instance=null;
private SingletonTest(){
}
public static SingletonTest getInstance(){
if(instance==null){
synchronized(SingletonTest.class){
if(instance==null){
instance=new SingletonTest();
}
}
}
return instance;
}
}
在代码中,SingletonTest拥有唯一实例,为static所修饰,构造方法为私有化,不提供该类的其他实例化,仅通过getInstance()方法来获取该类实例进行使用。
测试:
public class MySingletonTest {
@Test
public void test(){
SingletonTest singletonTest=SingletonTest.getInstance();
System.out.println(singletonTest.str);
singletonTest.str="123";
SingletonTest singletonTest2=SingletonTest.getInstance();
System.out.println(singletonTest.str);
System.out.println(singletonTest2.str);
}
}
输出结果:
由结果可知,singletonTest和singletonTest2指向的是同一个实例。