享元模式,运用共享技术有效地支持大量细粒度的对象。
package Flyweight; import java.util.HashMap; public class MainClass { public static void main(String[] args) { // TODO Auto-generated method stub int extrinsicstate = 22; FlyweightFactory f = new FlyweightFactory(); Flyweight fx = f.GetFlyweight("x"); fx.Operation(--extrinsicstate); Flyweight fy = f.GetFlyweight("y"); fy.Operation(--extrinsicstate); Flyweight fz = f.GetFlyweight("z"); fz.Operation(--extrinsicstate); UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight(); uf.Operation(--extrinsicstate); } } abstract class Flyweight { public abstract void Operation(int extrinsicstate); } class ConcreteFlyweight extends Flyweight { @Override public void Operation(int extrinsicstate) { // TODO Auto-generated method stub System.out.println("concreteFlyweight:"+extrinsicstate); } } class UnsharedConcreteFlyweight extends Flyweight { @Override public void Operation(int extrinsicstate) { // TODO Auto-generated method stub System.out.println("UnsharedConcreteFlyweight:"+extrinsicstate); } } class FlyweightFactory { private HashMap<String,Flyweight> flyweights = new HashMap<>(); public FlyweightFactory() { flyweights.put("x", new ConcreteFlyweight()); flyweights.put("y", new ConcreteFlyweight()); flyweights.put("z", new ConcreteFlyweight()); } public Flyweight GetFlyweight(String key) { return flyweights.get(key); } }