当前位置: 代码迷 >> Java相关 >> head first单件模式的例子是不是有有关问题
  详细解决方案

head first单件模式的例子是不是有有关问题

热度:91   发布时间:2016-04-22 21:05:45.0
head first单件模式的例子是不是有问题
文中说道巧克力工厂,类机构如下:

public class Chocolate{
private boolean empty;
private boolean boiled;
fill();
drain();
boile();


Q1:书中说到,如果同时存在两个Chocolate实例,可能发生糟糕的事情。

但是我认为,怎么会呢?两个实例,井水不犯河水的,有没有静态变量。

Q2:设计成单件模式之后。说没有问题了
但是我认为,设计成单件模式后,反而会出现问题啊,方法对变量的改变操作均没有加锁。

这么经典的书,我却看糊涂了,求各位大神给我好好讲讲啊!!
附书中:179-180.谢谢
------解决方案--------------------
完全的代码如下:

The Chocolate Factory - Can we improve it?【巧克力加工厂,我们该如何改善这段程序呢?】
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
  
public ChocolateBoiler() {     //public constructor!
empty = true;
boiled = false;
}
  
public void fill() {
if (isEmpty()) {
empty = false;
boiled = false;
// fill the boiler with a milk/chocolate mixture
}
}
 
public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
}
 
public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
}
  
public boolean isEmpty() {
return empty;
}
 
public boolean isBoiled() {
return boiled;
}
}


The Chocolate Factory - Singleton Version【巧克力加工厂,改善后的单例版本】
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;
// fill the boiler with a milk/chocolate mixture
}
}
 
public void drain() {
if (!isEmpty() && isBoiled()) {
// drain the boiled milk and chocolate
empty = true;
}
}
 
public void boil() {
if (!isEmpty() && !isBoiled()) {
// bring the contents to a boil
boiled = true;
}
}
  
public boolean isEmpty() {
return empty;
}
 
public boolean isBoiled() {
return boiled;
}
}
  相关解决方案