如何在php中实现享元模式?
这是它的定义:
使用共享来支持大量数据 有效地处理细粒度对象。
但我无法弄清楚它的确切含义。
你能用一个小演示来详细说明吗?
This is its definition:
Use sharing to support large numbers
of fine-grained objects efficiently.
But I can't figure out what it means exactly.
Can you elaborate with a tiny demo?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您需要大量特定类型的实例,则享元模式非常有用。您将所有这些实例的相同数据(内在状态)隔离到共享对象中。您只需将每个实例不同的数据保留在实例本身中(外部状态)。明显的好处是内存消耗更少。
这是游戏行业的常见模式,通常的例子是战场上的士兵。所有士兵都有相同的图形表示和相同的武器,但他们的位置和健康状况不同。外部状态将仅是他们在战场上的生命值和 x/y/z 坐标,而其他所有内容都将在蝇量级中。
这种模式的 PHP 实现很容易在网络上找到。例如
The Flyweight pattern is useful if you need a large number of instances of a particular type. You isolate the data that is the same for all these instances (the intrinsic state) into a shared object. You only keep the data that varies per instance in the instances themselves (the extrinsic state). The benefit is less memory consumption obviously.
It's a common pattern in the gaming industry where the usual example is Soldiers on the battle field. All Soldiers share the same graphical representation and the same weapons but their position and health is different. The extrinsic state would then only be their health and x/y/z coordinates on the battlefield while everything else would be in the Flyweight.
PHP Implementations for this pattern are easy to find on the web. For instance