设计模式之享元模式
Posted emoji-emoji
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之享元模式相关的知识,希望对你有一定的参考价值。
享元模式:运用共享技术有效地支持大量细粒度的对象。
public abstract class Flyweight { public abstract void method(int stamp); } public class ConcreteFlyweight extends Flyweight { @Override public void method(int stamp) { System.out.println("具体的Flyweight:" + stamp); } } public class UnsharedFlyweight extends Flyweight{ @Override public void method(int stamp) { System.out.println("非共享的具体Flyweight:"+stamp); } }
public class FlyweightFactory { private HashMap flyweights = new HashMap(); public FlyweightFactory() { flyweights.put("A", new ConcreteFlyweight()); flyweights.put("B", new ConcreteFlyweight()); } public Flyweight getFlyweight(String key) { return (Flyweight) flyweights.get(key); } }
public class FlyweightDemo { public static void main(String[] args) { int stamp = 10; FlyweightFactory factory = new FlyweightFactory(); Flyweight A = factory.getFlyweight("A"); A.method(stamp--); Flyweight B = factory.getFlyweight("B"); B.method(stamp--); Flyweight unsharedFlyweight = new UnsharedFlyweight(); unsharedFlyweight.method(stamp--); } }
以上是关于设计模式之享元模式的主要内容,如果未能解决你的问题,请参考以下文章