单例模式
单例模式分为饿汉式和懒汉式,通过构造方法私有化,类内部提供static方法获取实例化对象,这样不管外部如何操作永远都只有一个实例化对象饿汉式:
class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
public void print() {
System.out.println("singleton");
}
}
public class SingletonDemo {
public static void main(String[] args) {
Singleton instance = null;
instance = Singleton.getInstance();
instance.print();
}
}
特点:(立即加载)在系统加载类的时候就会自动提供Singleton类的实例化对象
属性是在有实例化对象产生之后才会被调用的,如果外部无法产生实例化对象,那就可以用上static
懒汉式:
class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if(instance == null){
instance = new Singleton();
}
return instance;
}
public void print() {
System.out.println("singleton");
}
}
public class SingletonDemo {
public static void main(String[] args) {
Singleton instance = null;
instance = Singleton.getInstance();
instance.print();
}
}
特点:(延迟加载)在第一次使用的时候进行实例化对象处理