随笔 - 117  文章 - 72  trackbacks - 0

声明:原创作品(标有[原]字样)转载时请注明出处,谢谢。

常用链接

常用设置
常用软件
常用命令
 

订阅

订阅

留言簿(7)

随笔分类(130)

随笔档案(123)

搜索

  •  

积分与排名

  • 积分 - 154450
  • 排名 - 389

最新评论

[关键字]:java,design pattern,设计模式,《Java与模式》学习,Flyweight Pattern,享元模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com) http://wintys.blogjava.net
[正文]:

享元模式-单纯享元:


package pattern.flyweight.simple;

import java.util.*;

/**
 * 单纯的享元
 * @version 2009-6-25
 * @author Winty(wintys@gmail.com)
 */
public class SimpleFlyweightTest{
    public static void main(String[] args){
        FlyweightFactory f = new FlyweightFactory();

        Flyweight a = f.factory(new Character('a'));
        a.operation("ex");

        Flyweight b = f.factory(new Character('b'));
        b.operation("ex");

        Flyweight c = f.factory(new Character('a'));
        c.operation("ex");

        f.checkFlyweight();
    }
}

/**
 * 抽象享元
 */
abstract class Flyweight{
    public abstract void operation(String extrinsicState);
}

/**
 * 具体享元
 */
class ConcreteFlyweight extends Flyweight{
    private Character intrinsicState;

    public ConcreteFlyweight(Character intrinsicState){
        this.intrinsicState = intrinsicState;
    }

    /**
     * 外蕴状态改变方法行为,但不会改变内蕴状态
     */
    @Override
    public void operation(String extrinsicState){
        String str = "intrinsic:" + intrinsicState;
        str += "   extrinsic:" + extrinsicState;
        System.out.println(str);
    }
}

/**
 * 享元工厂
 */
class FlyweightFactory{
    private Map<Character , Flyweight> map;

    public FlyweightFactory(){
        map = new HashMap<Character , Flyweight>();
    }

    public Flyweight factory(Character state){
        Flyweight flyweight = null;

        if(map.containsKey(state)){
            flyweight = map.get(state);
        }
        else{
            flyweight = new ConcreteFlyweight(state);
            map.put(state , flyweight);
        }

        return flyweight;
    }

    /**
     * 辅助方法
     */
    public void checkFlyweight(){
        Iterator<Map.Entry<Character , Flyweight>> it
            = map.entrySet().iterator();
        System.out.println("check flyweight:");
        while(it.hasNext()){
            Map.Entry<Character , Flyweight> entry = it.next();
            Character key = entry.getKey();
            System.out.println("key:" + key);
        }
    }
}

运行结果:
intrinsic:a   extrinsic:ex
intrinsic:b   extrinsic:ex
intrinsic:a   extrinsic:ex
check flyweight:
key:b
key:a
posted on 2009-06-29 22:52 天堂露珠 阅读(955) 评论(0)  编辑  收藏 所属分类: Pattern

只有注册用户登录后才能发表评论。


网站导航: