单例模式
singleton模式:确保内存中某个类的实例只有一个。
通过类变量实例化对象
public class SingleTest{
public static void main(String[] args){
singleton s1 = singleton.getInstance();
singleton s2 = singleton.getInstance();
System.out.println(s1==s2);
}
}
class singleton{
private static singleton singleton = new singleton();
//构造方法设置为私有,在外部不能直接使用new来实例化
private singleton(){
}
//通过getInstance来获得类的实例
public static singleton getInstance(){
return singleton;
}
}
滞后初始化实现单例,不能在多线程环境中使用
public class SingleTest{
public static void main(String[] args){
singleton s1 = singleton.getInstance();
singleton s2 = singleton.getInstance();
System.out.println(s1==s2);
}
}
class singleton{
private static singleton singleton = null;
private singleton(){
}
public static singleton getInstance(){
if(singleton == null){
singleton = new singleton();
}
return singleton;
}
}