目录
- 简介
- 角色
- UML类图
- java实现方式
- 总结
1. 简介
通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例
2. 角色:
自身又是工厂又是具体的对象
3. UML类图
4. java实现方式
4.1 饿汉式:空间换时间
/**
* @program: pattern
* @description: 饿汉式单例
* @author: chengqj
* @create: 2018-08-06 18:08
**/
public class Hungry {
private Hungry(){}
private static final Hungry hungry = new Hungry();
public static Hungry getInstance(){
return hungry;
}
}
4.2 懒汉式-方法锁
/**
* @program: pattern
* @description: 懒汉式方式一:直接方法锁
* @author: chengqj
* @create: 2018-08-06 18:13
**/
public class LazyOne {
private LazyOne(){}
private static LazyOne lazy = null;
public static synchronized LazyOne getInstance(){
if(lazy == null){
lazy = new LazyOne();
}
return lazy;
}
}
4.3 懒汉式-内部类
**
* @program: pattern
* @description: 懒汉式方式二:内部类方式
* @description:这种形式兼顾饿汉式的内存浪费,也兼顾synchronized性能问题
* @author: chengqj
* @create: 2018-08-06 18:16
**/
public class LazyTwo {
private boolean initialized = false;
private LazyTwo(){
synchronized (LazyTwo.class){
if(initialized == false){
initialized = !initialized;
}else{
throw new RuntimeException("单例已被侵犯");
}
}
}
public static final LazyTwo getInstance(){
return LazyHolder.LAZY;
}
private static class LazyHolder{
private static final LazyTwo LAZY = new LazyTwo();
}
}
4.4 注册式
/**
* @program: pattern
* @description: 注册式
* @author: chengqj
* @create: 2018-08-06 18:41
**/
public class Register {
private Register(){};
private static Map<String, Register> registerMap = new ConcurrentHashMap<>();
public static Register getInstance(String name) {
if (name == null) {
name = Register.class.getName();
}
if (registerMap.get(name) == null) {
registerMap.put(name,new Register());
}
return registerMap.get(name);
}
}
4.5 序列号方式
/**
* @program: pattern
* @description: 序列化方式
* @author: chengqj
* @create: 2018-08-06 19:12
**/
public class Seriable implements Serializable {
public final static Seriable INSTANCE = new Seriable();
private Seriable(){}
public static Seriable getInstance(){
return INSTANCE;
}
//确保式同一个对象
private Object readResolve(){
return INSTANCE;
}
}
4.6 枚举式
/**
* @program: pattern
* @description: 枚举式
* @author: chengqj
* @create: 2018-08-06 19:18
**/
public enum RegiterEnum {
INSTANCE,BLACK,WHITE;
public void getInstance(){}
}
5. 总结:
方式 | 特点 |
---|---|
饿汉式 | 空间换时间 |
懒汉式 | 时间换空间 |