首页 > 代码库 > 享元模式

享元模式

    享元模式(Flyweight Pattern),Flyweight在拳击比赛中是最轻量级别--蝇量级。享元模式以共享的方式支持大量的细粒度对象。

    享元模式在编辑系统中被大量使用,例如字母a会在许多的地方出现,尽管所出现的位置和字模风格不尽相同,但是都可以共享一个字母a的对象。

     Java中的String是final的,改变String的内容就是一个新的String了。只要是内容相同,多个String对象是可以共享一个String实例的。

     享元模式可以分为单纯享元模式和复合享元模式两种。

     单纯享元模式中,所有享元对象都是可以共享的。下面是单纯享元模式的类图:

     

      核心是FlyweightFactory,采取的是登记的工厂方式,用HashMap存储已经构造的ConcreteFlyweight。调用时先去查看HashMap是否已经存在,已存在则直接调用。不存在时先创建再添加到HashMap中以共享使用。

      Flyweight接口的示例代码:    

public abstract  class Flyweight{    public abstract  void operation(String state);}

      具体类ConcreteFlyweight的示例代码:

public class ConcreteFlyweight extends Flyweight{    private Character intrinsicState = null;    public ConcreteFlyweight(Character state){        this.intrinsicState = state;    }        public void operation(String state){      System.out.print( "\nIntrinsic State = " + intrinsicState +            ", Extrinsic State = " + state);    }}

        工厂类FlyweightFactory的示例代码:

public class FlyweightFactory{    private HashMap flies = new HashMap();    private Flyweight lnkFlyweight;    public FlyweightFactory(){    }        public synchronized Flyweight factory(Character state){     if (flies.containsKey(state)){            return (Flyweight)flies.get(state);    }    else{        Flyweight fly = new ConcreteFlyweight(state);            flies.put(state, fly);            return fly;        }    }        public void checkFlyweight(){     Flyweight fly ;        int i = 0;        System.out.println("\n==========checkFlyweight()=============");    for (Iterator it = flies.entrySet().iterator() ; it.hasNext(); ){        Map.Entry e = (Map.Entry) it.next();            System.out.println("Item " + (++i) + " : " + e.getKey());        }        System.out.println("==========checkFlyweight()=============");   }}

      客户端client的示例代码:

public class Client{    private static FlyweightFactory factory;    public static  void main(String[] args){     factory = new FlyweightFactory();    Flyweight fly = factory.factory(new Character(‘a‘));    fly.operation("First Call");            fly = factory.factory(new Character(‘b‘));    fly.operation("Second Call");            fly = factory.factory(new Character(‘a‘));    fly.operation("Third Call");            // intrinsic Flyweight    factory.checkFlyweight();   } }

       客户端client在创建2个对象”a”时实际上是共享了一个对象。

享元模式