public abstract class Flyweight {
public abstract void operation(int extrinsicstate);
}
public class ConcreteFlyweight extends Flyweight {
@Override
public void operation(int extrinsicstate) {
System.out.println("具体 flyweight : "+extrinsicstate);
}
}
public class UnsharedConcreteFlyweight extends Flyweight{
@Override
public void operation(int extrinsicstate) {
System.out.println("不共享的具体 flyweight : "+extrinsicstate);
}
}
public class FlyweightFactory {
private Hashtable flyweights = new Hashtable<Object, Object>();
public FlyweightFactory() {
flyweights.put("x", new ConcreteFlyweight());
flyweights.put("y", new ConcreteFlyweight());
flyweights.put("z", new ConcreteFlyweight());
}
public Flyweight getFlyweight(String key) {
return (Flyweight) flyweights.get(key);
}
}
public class DemoEnter {
public static void main(String[] args) {
int extrinsicstate = 22;
FlyweightFactory f = new FlyweightFactory();
Flyweight fx = f.getFlyweight("x");
fx.operation(--extrinsicstate);
Flyweight fy = f.getFlyweight("y");
fx.operation(--extrinsicstate);
Flyweight fz = f.getFlyweight("z");
fx.operation(--extrinsicstate);
UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
uf.operation(--extrinsicstate);
}
}