标签:mystra 设计模式 单件模式 singleton java
本文地址: http://blog.csdn.net/caroline_wendy/article/details/28595349
单件模式(singleton pattern) : 确保一个类只有一个实例, 并提供一个全局访问点.
单价模式包括3个部分: 私有构造器, 静态变量, 静态方法.
具体方法:
1. 标准的单例模式:
/** * @time 2014.6.5 */ package singleton; /** * @author C.L.Wang * */ public class Singleton { private static Singleton uniqueInstance; //静态变量 private Singleton() {} //私有构造函数 public static Singleton getInstance() { //静态方法 if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; } }
同步(synchronized)方法, 添加"synchronized", 会导致性能下降, 每次调用示例, 都需要同步, 但是使用简单.
/** * @time 2014.6.5 */ package singleton; /** * @author C.L.Wang * */ public class Singleton { private static Singleton uniqueInstance; //静态变量 private Singleton() {} //私有构造函数 public static synchronized Singleton getInstance() { //静态方法 if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; } }
急切(eagerly)方法, 开始时创建实例, 会在不需要时, 占用实例空间, 即占用空间时间过长.
/** * @time 2014.6.5 */ package singleton; /** * @author C.L.Wang * */ public class Singleton { private static Singleton uniqueInstance = new Singleton(); //静态变量 private Singleton() {} //私有构造函数 public static synchronized Singleton getInstance() { //静态方法 //if (uniqueInstance == null) //uniqueInstance = new Singleton(); return uniqueInstance; } }
/** * @time 2014.6.5 */ package singleton; /** * @author C.L.Wang * */ public class Singleton { private volatile static Singleton uniqueInstance; //静态变量 private Singleton() {} //私有构造函数 public static synchronized Singleton getInstance() { //静态方法 if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } } return uniqueInstance; } }
代码:
/** * @time 2014.6.5 */ package singleton; /** * @author C.L.Wang * */ public class ChocolateBoiler { //巧克力锅炉 private boolean empty; private boolean boiled; public static ChocolateBoiler uniqueInstance; //静态变量 private ChocolateBoiler() { //私有构造函数 empty = true; boiled = false; } public static ChocolateBoiler getInstance() { //静态方法 if (uniqueInstance == null) uniqueInstance = new ChocolateBoiler(); return uniqueInstance; } public void fill() { //填满 if (isEmpty()) { empty = false; boiled = false; } } public void drain() { //倾倒 if (!isEmpty() && isBoiled()) empty = true; } public void boil() { //煮 if (!isEmpty() && !isBoiled()) { boiled = true; } } public boolean isEmpty() { return empty; } public boolean isBoiled() { return boiled; } }
设计模式 - 单件模式(singleton pattern) 详解,布布扣,bubuko.com
设计模式 - 单件模式(singleton pattern) 详解
标签:mystra 设计模式 单件模式 singleton java
原文地址:http://blog.csdn.net/caroline_wendy/article/details/28595349