1,单例设计模式:保证内存中只有一个对象;
2,方法1(饿汉式):
a,控制类的创建,不让其他类来创建本类的对象;
b,本类中定义一个本类的对象,Singleton s;
c,提供公共的访问方式,public static Singleton getINstance(){return s}
案例:
class Singleton{
//1,私有构造
private Singleton() {}
//2,创建本类对象;
private static Singleton s = new Singleton();
//3,对外提供公共访问方法;
public static Singleton getInstance() {
return s;
}
}
3,方法2(懒汉式)
class Test{
private Test(){}
private static Test s ;
public static Test getInstance(){
if (s == null){
s = new Test();
}
return s;
}
}
方法3
class Test{
private Test() {
}
public final static Test t = new Test();
}
网友评论