目录
单例模式
一个类只允许产生一个实例化对象
那怎么样限制对象的产生个数
对象的产生是通过构造方法产生对象
- private声明构造方法
- 单例类内部提供一个产生好的静态对象
- 单例类内部提供静态方法返回唯一的一个对象
单例设计模式有两种:
- 饿汉式单例模式
- 懒汉式单例模式
饿汉式单例
class Singleton{
private static final Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getSingleton() {
return singleton;
}
public void print(){
System.out.println("hello");
}
}
懒汉式单例
当第一次去使用Singleton对象时才会产生实例化对象
class Singleton{
private static Singleton singleton;
private Singleton(){}
public static Singleton getSingleton() {
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
public void print(){
System.out.println("hello");
}
}