设计模式-单例
- 单例模式保证了 系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使
用单例模式可以提高系统性能 - 实例化一个单例类的时候,必须使用相应的获取对象的方法,而不是使用 new
- 单例模式 使用的场景:需要 频繁的进行创建和销毁的对象、创建对象时耗时过多或耗费资源过多(即:重量级
对象),但又经常用到的对象、 工具类对象、频繁访问数据库或文件的对象(比如 数据源、session 工厂等)
public class SingletonTest {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
Singleton instance1 = Singleton.getInstance();
System.out.println(instance==instance1);
System.out.println(instance.hashCode());
System.out.println(instance1.hashCode());
}
}
class Singleton{
private Singleton(){}
private static Singleton singleton;
static {
singleton =new Singleton();
}
public static Singleton getInstance(){
return singleton;
}
}
class Singleton1{
private static volatile Singleton1 getInstance;
private Singleton1(){}
public static Singleton1 singleton1(){
if(getInstance==null){
synchronized (Singleton1.class){
if(getInstance==null){
getInstance=new Singleton1();
}
}
}
return getInstance;
}
}
class Singleton2{
private Singleton2(){}
private static class getInstance{
private static final Singleton2 INSTANCE =new Singleton2();
}
public static Singleton2 getInstance(){
return getInstance.INSTANCE;
}
}
enum Singleton3{
INSTANCE;
public void sayOK(){
System.out.println("ok");
}
}