如何在php中实现享元模式?

发布于 2024-08-22 18:18:00 字数 124 浏览 2 评论 0原文

这是它的定义:

使用共享来支持大量数据 有效地处理细粒度对象。

但我无法弄清楚它的确切含义。

你能用一个小演示来详细说明吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南笙 2024-08-29 18:18:00

如果您需要大量特定类型的实例,则享元模式非常有用。您将所有这些实例的相同数据(内在状态)隔离到共享对象中。您只需将每个实例不同的数据保留在实例本身中(外部状态)。明显的好处是内存消耗更少。

这是游戏行业的常见模式,通常的例子是战场上的士兵。所有士兵都有相同的图形表示和相同的武器,但他们的位置和健康状况不同。外部状态将仅是他们在战场上的生命值和 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文