更新时间:2022-09-07 18:12:40
运用共享技术有效地支持大量细粒度的对象。
当都具备下列情况时,使用Flyweight模式:
package com.lyz.design.flyweight; /** * Flyweight * @author binghe * */ public interface Flyweight { void action(int arg); }
package com.lyz.design.flyweight; /** * ConcreteFlyweight * @author binghe * */ public class FlyweightImpl implements Flyweight { public void action(int arg) { // TODO Auto-generated method stub System.out.println("参数值: " + arg); } }
package com.lyz.design.flyweight; import java.util.HashMap; import java.util.Map; /** * FlyweightFactory * @author binghe * */ public class FlyweightFactory { private static Map flyweights = new HashMap(); public FlyweightFactory(String arg) { flyweights.put(arg, new FlyweightImpl()); } public static Flyweight getFlyweight(String key) { if (flyweights.get(key) == null) { flyweights.put(key, new FlyweightImpl()); } return (Flyweight) flyweights.get(key); } public static int getSize() { return flyweights.size(); } }
package com.lyz.design.flyweight; /** * Test * @author binghe */ public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Flyweight fly1 = FlyweightFactory.getFlyweight("a"); fly1.action(1); Flyweight fly2 = FlyweightFactory.getFlyweight("a"); System.out.println(fly1 == fly2); Flyweight fly3 = FlyweightFactory.getFlyweight("b"); fly3.action(2); Flyweight fly4 = FlyweightFactory.getFlyweight("c"); fly4.action(3); Flyweight fly5 = FlyweightFactory.getFlyweight("d"); fly4.action(4); System.out.println(FlyweightFactory.getSize()); } }