在享元模式中将静态实例分配给非静态实例
-
22-10-2019 - |
题
我正在查看 Flyweight 示例代码 http://www.oodesign.com/flyweight-pattern-wargame-example-java-sourcecode.html 并想知道当我们分配静态实例时它是如何工作的(SOLDIER
如上面的站点)到非静态士兵实例 SoldierClient
我们真的减少了对象的大小吗? SoldierClient
会以某种方式保存一份副本 SOLDIER
每个实例中 SoldierClient
我们创建的对象?
编辑:
在方法中 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
}
解决方案
一个 SoldierClient
不举行 复制 的 SOLDIER
, ,它拥有一个 参考 至 SOLDIER
, , 和 每一个 SoldierClient
有参考 相同的 SOLDIER
.
回答编辑
每个士兵的位置都在 SoldierClient
实例(currentLocationX
和 currentLocationY
特性)。这些属性的代码注释也将其阐明:“该状态由客户维护”(即,”该状态在 SoldierImp
实例”)。
一切都在 moveSoldier
的参数:没有 SoldierImp
实例状态。将其视为静态实用方法。坐标由 SoldierClient
实例;他们从不被 SoldierImp
- 使用。
其他提示
正如文档中提到的:
解决方案是将士兵的共同状态保持在共享对象中
实际上,每个 SolderClient 都有对 SOLDIER 的引用而不是副本。在每个 SolderClient 变量中 士兵 士兵 仅引用一个对象蚂蚁,它对于所有客户端都是相同的。
由于享元模式使用单例模式,也许你可以先检查一下:
每个士兵实例都有一个 参考 到士兵对象。在这种情况下,它们都指向同一实例。您会注意到,对于每次拨打SoldierFactory的电话,都会返回同一士兵对象 - 只有一个呼叫士兵的构造师。
也可以看看 辛格尔顿