概念:运用共享技术有效地支持大量细粒度的对象
核心:共享内存,划分内部状态与外部状态,外部状态在使用的时候传递进来
作用:本地缓存
享元模式结构图

java代码
public class FlyWeightTest {public static void main(String[] args) {FlyWeightFactory f = new FlyWeightFactory();int index = 22;FlyWeight x = f.GetFlyWeight("X");x.Operation(index--);FlyWeight y = f.GetFlyWeight("Y");x.Operation(index--);FlyWeight z = f.GetFlyWeight("Z");x.Operation(index--);UnSharedConcreteFlyWeight unSharedConcreteFlyWeight = new UnSharedConcreteFlyWeight();unSharedConcreteFlyWeight.Operation(index--);}}//享元工厂public class FlyWeightFactory {Map<String, FlyWeight> map = new HashMap<>();public FlyWeight GetFlyWeight(String key){return map.get(key);}public FlyWeightFactory(){map.put("X", new ConcreteFlyWeight());map.put("Y", new ConcreteFlyWeight());map.put("Z", new ConcreteFlyWeight());}}public abstract class FlyWeight {public abstract void Operation(int index);}public class UnSharedConcreteFlyWeight extends FlyWeight {@Overridepublic void Operation(int index) {System.out.println("不共享的类" + index);}}public class ConcreteFlyWeight extends FlyWeight {@Overridepublic void Operation(int index) {System.out.println("共享的类" + index);}}
