[关键字]:java,design pattern,设计模式,《Java与模式》学习,Flyweight Pattern,享元模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty ([email protected]) http://wintys.blogjava.net
[正文]:
一个单纯享元的例子:咖啡摊(Coffee Stall)
package pattern.flyweight.coffee.stall;
import java.util.*;
/**
* 一个单纯享元的例子
* 咖啡摊:Coffee Stall
* @version 2009-6-25
* @author Winty(
[email protected])
*/
public class CoffeeStallTest{
public static void main(String[] args){
FlavorFactory f = FlavorFactory.getInstance();
Order o1,o2,o3;
o1 =f.factory("Black Coffee");
o2 = f.factory("Espresso");
o3 = f.factory("Black Coffee");
o1.serve();
o2.serve();
o3.serve();
f.checkFlyweight();
}
}
/**
* 抽象享元角色
*/
abstract class Order{
public abstract void serve();
public abstract String getFlavor();
}
/**
* 具体享元角色
*/
class Flavor extends Order{
private String flavor;//内蕴状态
public Flavor(String flavor){
this.flavor = flavor;
}
@Override
public void serve(){
System.out.println("serve " + flavor);
}
@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);
}
}
}
运行结果:
serve Black Coffee
serve Espresso
serve Black Coffee
check flyweight:
key:Black Coffee
key:Espresso