[关键字]:java,design pattern,设计模式,《Java与模式》学习,阎宏,Ph.D,Flyweight Pattern,享元模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty ([email protected]) http://wintys.blogjava.net
[正文]:
一个有外蕴状态的单纯享元例子:咖啡屋(Coffee Shop)
package pattern.flyweight.coffee.shop;
import java.util.*;
/**
* 一个有外蕴状态的单纯享元例子
* 咖啡屋:Coffee Shop
* @version 2009-6-25
* @author Winty(
[email protected])
*/
public class CoffeeShopTest{
public static void main(String[] args){
FlavorFactory f = FlavorFactory.getInstance();
Table t1,t2;
t1 = new Table(101);
t2 = new Table(102);
Order o1,o2,o3;
o1 =f.factory("Black Coffee");
o2 = f.factory("Espresso");
o3 = f.factory("Black Coffee");
o1.serve(t1);
o2.serve(t1);
o3.serve(t2);
f.checkFlyweight();
}
}
/**
* 抽象享元角色
*/
abstract class Order{
public abstract void serve(Table table);
public abstract String getFlavor();
}
/**
* 具体享元角色
*/
class Flavor extends Order{
private String flavor;//内蕴状态
public Flavor(String flavor){
this.flavor = flavor;
}
@Override
public void serve(Table table){
System.out.println("serve " + flavor + " to " + table.getNum());
}
@Override
public String getFlavor(){
return flavor;
}
}
/**
* 享元工厂:使用单例模式实现
*/
class FlavorFactory{
private static FlavorFactory f = new FlavorFactory();
private Map<String , Order> map;
public FlavorFactory(){
map = new HashMap<String , Order>();
}
public static FlavorFactory getInstance(){
return f;
}
public Order factory(String flavor){
Order order = null;
if(map.containsKey(flavor)){
order = map.get(flavor);
}
else{
order = new Flavor(flavor);
map.put(flavor , order);
}
return order;
}
/**
* 辅助方法
*/
public void checkFlyweight(){
Iterator<Map.Entry<String , Order>> it
= map.entrySet().iterator();
System.out.println(""ncheck flyweight:");
while(it.hasNext()){
Map.Entry<String , Order> entry = it.next();
String key = entry.getKey();
System.out.println("key:" + key);
}
}
}
/**
* 外蕴状态类
*/
class Table{
private int num;
public Table(int num){
setNum(num);
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num = num;
}
}
运行结果:
serve Black Coffee to 101
serve Espresso to 101
serve Black Coffee to 102
check flyweight:
key:Black Coffee
key:Espresso