首页 > 代码库 > 设计模式——享元模式

设计模式——享元模式

Flyweight 直译为蝇量。就其表示的模式来说,翻译成享元,确实是不错的

package designpattern.structure.flyweight;public interface Flyweight {    void action(int arg);}package designpattern.structure.flyweight;public class FlyweightImpl implements Flyweight {    public void action(int arg) {        // TODO Auto-generated method stub        System.out.println("FlyweightImpl.action()");    }}package designpattern.structure.flyweight;import java.util.HashMap;import java.util.Map;public class FlyweightFactory {    private static Map<String,Flyweight> flyweights = new HashMap<String,Flyweight>();           public FlyweightFactory(String arg) {        flyweights.put(arg, new FlyweightImpl());    }       public static Flyweight getFlyweight(String key) {        if (flyweights.get(key) == null) {            flyweights.put(key, new FlyweightImpl());        }        return flyweights.get(key);    }    public static int getSize() {        return flyweights.size();    }}package designpattern.structure.flyweight;public class Client {    /**     *      * Fly微Weight量模式 —— 将小对象缓存起来的艺术。、、     *      */    public static void main(String[] args) {        Flyweight fly1 = FlyweightFactory.getFlyweight("a");        fly1.action(1);               Flyweight fly2 = FlyweightFactory.getFlyweight("a");        System.out.println(fly1 == fly2);               Flyweight fly3 =FlyweightFactory.getFlyweight("b");        fly3.action(2);               Flyweight fly4 = FlyweightFactory.getFlyweight("c");        fly4.action(3);               Flyweight fly5 =FlyweightFactory.getFlyweight("d");        fly4.action(4);               System.out.println(FlyweightFactory.getSize());    }}

 

总结:

1 主要就是两个角色元或者说pojo角色—— 主要属性是其内部状态;    工厂角色,用来获取‘元’ 

2 ‘享’ 的具体实现是—— 工厂获取‘元’的时候,如果已经已经创建过,则直接取出返回;如果没,则创建并加入缓存,再返回