[关键字]:java,design pattern,设计模式,《Java与模式》学习,Flyweight Pattern,享元模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty ([email protected]) http://wintys.blogjava.net
[正文]:
享元模式-单纯享元:
package pattern.flyweight.simple;
import java.util.*;
/**
* 单纯的享元
* @version 2009-6-25
* @author Winty(
[email protected])
*/
public class SimpleFlyweightTest{
public static void main(String[] args){
FlyweightFactory f = new FlyweightFactory();
Flyweight a = f.factory(new Character('a'));
a.operation("ex");
Flyweight b = f.factory(new Character('b'));
b.operation("ex");
Flyweight c = f.factory(new Character('a'));
c.operation("ex");
f.checkFlyweight();
}
}
/**
* 抽象享元
*/
abstract class Flyweight{
public abstract void operation(String extrinsicState);
}
/**
* 具体享元
*/
class ConcreteFlyweight extends Flyweight{
private Character intrinsicState;
public ConcreteFlyweight(Character intrinsicState){
this.intrinsicState = intrinsicState;
}
/**
* 外蕴状态改变方法行为,但不会改变内蕴状态
*/
@Override
public void operation(String extrinsicState){
String str = "intrinsic:" + intrinsicState;
str += " extrinsic:" + extrinsicState;
System.out.println(str);
}
}
/**
* 享元工厂
*/
class FlyweightFactory{
private Map<Character , Flyweight> map;
public FlyweightFactory(){
map = new HashMap<Character , Flyweight>();
}
public Flyweight factory(Character state){
Flyweight flyweight = null;
if(map.containsKey(state)){
flyweight = map.get(state);
}
else{
flyweight = new ConcreteFlyweight(state);
map.put(state , flyweight);
}
return flyweight;
}
/**
* 辅助方法
*/
public void checkFlyweight(){
Iterator<Map.Entry<Character , Flyweight>> it
= map.entrySet().iterator();
System.out.println("check flyweight:");
while(it.hasNext()){
Map.Entry<Character , Flyweight> entry = it.next();
Character key = entry.getKey();
System.out.println("key:" + key);
}
}
}
运行结果:
intrinsic:a extrinsic:ex
intrinsic:b extrinsic:ex
intrinsic:a extrinsic:ex
check flyweight:
key:b
key:a