首页 > 其他 > 详细

设计模式——享元模式

时间:2014-08-17 01:03:51      阅读:330      评论:0      收藏:0      [点我收藏+]

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

设计模式——享元模式,布布扣,bubuko.com

设计模式——享元模式

原文:http://www.cnblogs.com/FlyAway2013/p/3917177.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!