关于单例模式的2种

单例模式
在开发中,当一个类完全不需要有多个实例时,可以使用单例模式来保证一个类只有一个对象。
实现形式主要有两种,饿汉式和懒汉式。
所谓的饿汉式就是在声明实例的时候直接初始化对象,而懒汉式是先声明一个空对象,在静态方法中实例化该对象并返回。在实际开发中用的更多的是饿汉写法,可以对这个类加锁,在变量声明的时候就初始化。

饿汉式:
public class Singleton {
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}

懒汉式:
public class Singleton {
private Singleton(){}
private static Singleton instance = null;
public static Singleton getInstance(){
if (instance==null)
instance=new Singleton();
return instance;
}
}

猜你喜欢

转载自www.cnblogs.com/bloggerzzh/p/9816919.html