http://alicharles.com/article/jdk-flyweight-pattern/
http://www.cnblogs.com/java-my-life/archive/2012/04/26/2468499.html
示例:
-
import java.util.HashMap;
-
import java.util.Iterator;
-
import java.util.Map;
-
-
public class Test {
-
-
-
-
public static void main(String[] args) {
-
FlyweightFactory f = new FlyweightFactory();
-
-
Flyweight fly = f.factory("aba");
-
fly.operation("charles");
-
-
f.checkFlyweight();
-
-
}
-
}
-
-
-
-
-
abstract class Flyweight {
-
public abstract void operation(String extrinsicState);
-
}
-
-
-
-
-
class ConcreteFlyweight extends Flyweight {
-
-
private Character inState;
-
-
public ConcreteFlyweight(Character inState) {
-
this.inState = inState;
-
}
-
-
-
-
-
@Override
-
public void operation(String extState) {
-
String str = "inState:" + inState + ";extState:" + extState;
-
System.out.println(str);
-
}
-
-
}
-
-
-
-
-
class CompositeFlyweight extends Flyweight {
-
private Map<Character, Flyweight> map;
-
-
public CompositeFlyweight() {
-
map = new HashMap<Character, Flyweight>();
-
}
-
-
public void add(Character c, Flyweight fly) {
-
map.put(c, fly);
-
}
-
-
@Override
-
public void operation(String extState) {
-
Iterator<Map.Entry<Character, Flyweight>> it = map.entrySet().iterator();
-
while (it.hasNext()) {
-
Map.Entry<Character, Flyweight> entry = it.next();
-
Flyweight fly = entry.getValue();
-
fly.operation(extState);
-
}
-
}
-
}
-
-
-
-
-
class FlyweightFactory {
-
private Map<Character, Flyweight> map;
-
-
public FlyweightFactory() {
-
map = new HashMap<Character, Flyweight>();
-
}
-
-
-
-
-
public Flyweight factory(Character state) {
-
-
Flyweight flyweight;
-
-
if (map.containsKey(state)) {
-
flyweight = map.get(state);
-
} else {
-
flyweight = new ConcreteFlyweight(state);
-
map.put(state, flyweight);
-
}
-
-
return flyweight;
-
}
-
-
-
-
-
public Flyweight factory(String compositeState) {
-
CompositeFlyweight composite = new CompositeFlyweight();
-
-
for (int i = 0; i < compositeState.length(); i++) {
-
Character c = new Character(compositeState.charAt(i));
-
composite.add(c, this.factory(c));
-
}
-
-
return composite;
-
}
-
-
-
-
-
public void checkFlyweight() {
-
Iterator<Map.Entry<Character, Flyweight>> it = map.entrySet().iterator();
-
System.out.println("checkFlyweight:");
-
while (it.hasNext()) {
-
Map.Entry<Character, Flyweight> entry = it.next();
-
Character key = entry.getKey();
-
System.out.println("key:" + key);
-
}
-
}
-
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2136280/
,如需转载,请注明出处,否则将追究法律责任。