单例设计模式
饿汉式单例
class Singleton{
//类内部提供实例化对象
private static final Singleton SINGLETON = new Singleton();
//构造方法私有化
//类外部无法产生实例化对象
private Singleton(){}
//对象方法
public static Singleton getSingleton(){
return SINGLETON;
}
public void print(){
System.out.println("hello world");
}
}
public class Test{
public static void main(String[] args) {
Singleton SINGLETON = Singleton.getSingleton();
SINGLETON.print();
}
}
懒汉式单例
class Singleton{
private static Singleton INSTANCE;
//private声明构造
private Singleton(){}
public static Singleton getSingleton(){
if(INSTANCE == null){//表示此时还没有实例化
INSTANCE = new Singleton();
}
return INSTANCE;
}
public void print(){
System.out.println("hello world");
}
}
public class Test{
public static void main(String[] args) {
Singleton INSTANCE = Singleton.getSingleton();
INSTANCE.print();
}
}
多例设计模式