单例模式:饿汉式与懒汉式

单例模式

唯一的实例

注意:私有化构造器自行创建(含有一个该类的静态变量来保存唯一实例)必须自行向整个系统提供这个实例(对外提供获取该实例对象的方式:1、直接暴露2、静态变量的get方法获取)

几种常见形式

饿汉式:直接创建对象,不存在线程安全问题

直接实例化饿汉式简洁直观

枚举式 最简洁

静态代码块饿汉式 适合复杂实例化

饿汉式方式一:

public class Singleton1 {
public static final Singleton1 SINGLETON1 = new Singleton1();
private Singleton1() {
}
}

饿汉式方式二:

public enum Singleton2 {
SINGLETON;
}

饿汉式方式三:


public class Singleton3 {
public static final Singleton3 SINGLETON3;
private String info;
static {
try {
Properties properties = new Properties();
properties.load(Singleton3.class.getClassLoader().getResourceAsStream("singleton.properties"));
SINGLETON3 = new Singleton3(properties.getProperty("info"));
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
private Singleton3(String info){
this.info= info;
}
@Override
public String toString() {
return "Singleton3 [info=" + info + "]";
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

懒汉式:延迟创建对象

线程不安全 适用于单线程

线程安全 适用于多线程

静态内部类形式 适用于多线程

线程安全


public class Singleton4 {
private static Singleton4 singleton4;
private Singleton4() {
}
public static Singleton4 getSingleton() {
if (singleton4==null) {
synchronized (Singleton4.class) {

if (singleton4 == null) {
return singleton4 = new Singleton4();
}
}
}
return singleton4;
}
}

静态内部类方法


public class Singleton5 {
private Singleton5(){
}
private static class Single{
private final static Singleton5 SINGLETON = new Singleton5();
}
public static Singleton5 getSingleton() {
return Single.SINGLETON;
}
}

总结

饿汉式:枚举形式最简单

懒汉式:静态内部类形式最简单

posted @ 2019-05-23 23:56  北风以北  阅读(87)  评论(0编辑  收藏  举报