大话设计模式之享元模式

来源:互联网 发布:c语言编写库文件 编辑:程序博客网 时间:2024/06/05 13:25

享元模式,运用共享技术有效地支持大量细粒度的对象。


package Flyweight;import java.util.HashMap;public class MainClass {public static void main(String[] args) {// TODO Auto-generated method stubint 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 {@Overridepublic void Operation(int extrinsicstate) {// TODO Auto-generated method stubSystem.out.println("concreteFlyweight:"+extrinsicstate);}}class UnsharedConcreteFlyweight extends Flyweight {@Overridepublic void Operation(int extrinsicstate) {// TODO Auto-generated method stubSystem.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);}}

如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用;还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。