单例模式
2018-09-04 本文已影响0人
gentel_liao
饿汉式
public class SingletonOne {
//1.创建类中私有构造
private SingletoneOne(){
}
//2.创建该类型的私有静态实例
private static SingletonOne instance = new singletonOne();
//3.创建公有的静态方法返回静态实例对象
public static SingletonOne getInstance(){
return instance;
}
}
懒汉式
public class SingletonOne {
//1.创建类中私有构造
private SingletoneOne(){
}
//2.创建该类型的私有静态实例
private static SingletonOne instance = null;
//3.创建公有的静态方法返回静态实例对象
public static SingletonOne getInstance(){
if (instance == null){
instance = new SingletonOne();
}
return instance;
}
}