享元模式11(14)
Posted zzlcome
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了享元模式11(14)相关的知识,希望对你有一定的参考价值。
池技术:复用原对象
package structural; import java.util.HashMap; public class FlyweightPool public static void main(String[] args) int extrinsic = 22; Flyweight fx = FlyweightFactory.getFlyweight("X轴"); fx.opration(extrinsic); Flyweight fy = FlyweightFactory.getFlyweight("Y轴"); fy.opration(++extrinsic); Flyweight fz = FlyweightFactory.getFlyweight("Z轴"); fz.opration(++extrinsic); Flyweight fx1 = FlyweightFactory.getFlyweight("X轴"); fx1.opration(extrinsic); UnShareableFlyweight un = new UnShareableFlyweight("X轴"); un.opration(++extrinsic); abstract class Flyweight //内部状态 public String instrinsic; //外部状态 protected final String extrinsic; //享元角色必须接收外部状态 public Flyweight(String extrinsic) this.extrinsic = extrinsic; public void opration(int extrinsic) public String getInstrinsic() return instrinsic; public void setInstrinsic(String instrinsic) this.instrinsic = instrinsic; class ConcreteFlyweight extends Flyweight public ConcreteFlyweight(String extrinsic) super(extrinsic); @Override public void opration(int extrinsic) super.opration(extrinsic); System.out.println("具体flyweight:"+extrinsic); class UnShareableFlyweight extends Flyweight public UnShareableFlyweight(String extrinsic) super(extrinsic); @Override public void opration(int extrinsic) super.opration(extrinsic); System.out.println("不共享的flyweight:"+extrinsic); class FlyweightFactory private static HashMap<String,Flyweight> pool = new HashMap<String,Flyweight>(); public static Flyweight getFlyweight(String extrinsic) Flyweight flyweight = null; if(pool.containsKey(extrinsic)) flyweight = pool.get(extrinsic); System.out.print("已有 " + extrinsic + " 直接从池中取---->"); else flyweight = new ConcreteFlyweight(extrinsic); pool.put(extrinsic, flyweight); System.out.print("创建 " + extrinsic + " 并从池中取出---->"); return flyweight;
以上是关于享元模式11(14)的主要内容,如果未能解决你的问题,请参考以下文章