楼主: 
H45 (!H45)   
2008-12-08 17:08:01※ 引述《hsnucsc (hsnugo)》之铭言:
: 最近在看Head First OOA&D
: 他有一个例子是
: Guitar              GuitarSpec        Inventory       FindGuitar(main的所在)
: =========          =============     ===========      ==========
: serialNumber        builder            guitars         inventory
: price               model
: GuitarSpec          type
: getSerialNumber()   getBuilder()      addGuitar()
: setprice()          getModel()        getGuitar()
: getSpec()           getType           search()
: 原本search()是写成
:   public List search(GuitarSpec searchSpec)
:   {
:     List matchingGuitars = new LinkedList();
:     for(Iterator i = guitars.iterator(); i.hasNext(); )
:     {
:       Guitar guitar = (Guitar)i.next();
:       GuitarSpec = guitar.getSpec();
:       if(searchSpec.getBuilder() != guitarSpec.getBuilder())
:         continue;
:       if(searchSpec.getModel() != guitarSpec.getModel())
:         continue;
:       if(searchSpec.getType() != guitarSpec.getType())
:         continue;
:       matchingGuitars.add(guitar);//builder, model, type都一样的话 就加进list
:     }
:     return matchingGuitars;
:   }
: 但是这样一来 如果GuitarSpec要加入其他特性 就必须更改Inventory.search()
: 所以他把两个GuitarSpec的比较
: 委派(delegate)给GuitarSpec
: 于是GuitarSpec多了下面这个method
:   public boolean matches(GuitarSpec spec)
:   {
:     if(builder != spec.getBuilder())
:       return false;
:     if(model != spec.getModel())
:       return false;
:     if(type != spec.getType())
:       return false;
:     if(backWood != spec.getBackWood())
:       return false;
:     return true;
:   }
: =========================================================================
: 我大致上知道
: 通常物件是名词
: 而他的method则是动词 是那个物件可以做的动作
: ex: Dog
:    ======
:    eat()
:    drink()
:    sleep()
: 但是如果是俄罗斯方块中的 Sqare
: 应该是sqare 有rotate() 然后我是叫sqare自己旋转
: 还是说应该是player拥有roate(这个method)去旋转sqare
Player 会旋转吗? Sqare 会旋转吗?
看来是 Player 会旋转 Sqare 而且 Sqare 会旋转自己。
这样分析看起来,Player 必须拥有 Sqare 的资讯才有办法旋转 Sqare
但是 Sqare 只要旋转自己就好。
所以将 Sqare 的 rotate 方法放在 Sqare 比较好
优于将 rotate 方法放在 Player。
当 Player 想要旋转 Sqare 的时候,则委派 Sqare 去做 rotate 即可。
即:
        Player                  Sqare
        ============            ========
        sqare: Sqare            rotate()