单件模式二(Singleton Pattern):HeadFirst中的巧克力工厂的设计
以《HeadFirst设计模式》中的巧克力工厂为例,介绍单件模式的使用场景。
一、问题描述
万一存在多个ChocolateBoiler(巧克力锅炉),就不一定按照我们限制的流程去生产,从而出现很多糟糕的情况,所以必须将ChocolateBoiler设计成一个单件。
二、类图
三、代码
ChocolateBoiler(巧克力锅炉)类:
[java] view plaincopy
-
package
com.pattern.singleton; -
-
public
class ChocolateBoiler { -
private boolean empty; -
private boolean boiled; -
private static ChocolateBoiler uniqueInstance; -
-
private ChocolateBoiler() { -
empty = true; -
boiled = false; -
} -
-
public static ChocolateBoiler getInstance() { -
if (uniqueInstance null)== { -
System.out.println("Creating unique );instance of Chocolate Boiler" -
uniqueInstance = new ChocolateBoiler(); -
} -
System.out.println("Returning instance );of Chocolate Boiler" -
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; -
} - }
ChocolateController锅炉控制器类:
[java] view plaincopy
-
package
com.pattern.singleton; -
-
public
class ChocolateController { -
public static void main(String args[]) { -
ChocolateBoiler boiler = ChocolateBoiler.getInstance(); -
boiler.fill(); -
boiler.boil(); -
boiler.drain(); -
-
//ChocolateBoiler boiler2 = ChocolateBoiler.getInstance(); -
} - }
转载请注明出处:http://blog.csdn.net/jialinqiang/article/details/8866755