2011-10-18 60 views
0

我正在浏览位于http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html的Flyweight示例代码,并且想知道当我们将静态实例(如上述网站中的SOLDIER)分配给非静态士兵时它是如何工作的在SoldierClient实例我们是否真的减小了对象大小,因为每个SoldierClient都会以某种方式持有我们创建的每个SoldierClient对象中的SOLDIER实例副本?以享元模式向静态实例分配静态实例

编辑:

在该方法中moveSoldier() 它说

//从先前的位置
删除士兵表示//然后渲染在新位置的士兵表示

怎么来的这不会影响在类WarGame

中创建的所有对象
package flyweight; 

public class SoldierImp implements Soldier { 

    /** 
    * Intrinsic State maintained by flyweight implementation 
    * Solider Shape (graphical represetation) 
    * how to display the soldier is up to the flyweight implementation 
    */ 
    private Object soldierGraphicalRepresentation; 

    /** 
    * Note that this method accepts soldier location 
    * Soldier Location is Extrinsic and no reference to previous location 
    * or new location is maintained inside the flyweight implementation 
    */ 
    public void moveSoldier(int previousLocationX, int previousLocationY, 
      int newLocationX, int newLocationY) { 

     // delete soldier representation from previous location 
     // then render soldier representation in new location 
    } 

回答

3

一个SoldierClient不持有副本SOLDIER,它拥有一个参考SOLDIER,并SoldierClient持有至相同SOLDIER参考。

接听编辑

每个士兵的位置在SoldierClient实例(currentLocationXcurrentLocationY属性)举行。这些属性的代码注释也说明了这种情况:“该状态由客户端维护”(即,“该状态不在SoldierImp实例中”)。

一切都在moveSoldier的参数:没有SoldierImp实例状态。把它看作是一种静态的实用方法。坐标由SoldierClient实例提供;他们永远不会被SoldierImp存储 - 只是使用。

+0

+1见,但在这里,我的困惑是,如果我们改变引用的属性,也应该体现在静态对应,但在这种情况下,它不? – coder9

+0

@ coder9您链接的代码永远不会更改引用的属性;实际上参考*有*没有属性。 –

+0

问题编辑如上。谢谢 – coder9

1

作为文档中提到:

的解决办法是保持战士的共同状态在共享 对象

真的每一SolderClient具有参照SOLDIER不是副本。在每一个SolderClient中,变量士兵士兵只是针对一个对象而言,它对所有客户都是一样的。

由于享元模式使用Singleton模式也许你可以先检查一下:

http://www.oodesign.com/singleton-pattern.html

1

每个SoldierClient实例都有一个参考一个士兵的对象。在这种情况下,它们都指向相同的实例。您会注意到,每次调用SoldierFactory时,都会返回同一个Soldier对象 - 只有一个调用Soldier的构造函数。

Singleton