c++ - C++ 中的适配器公共(public)函数 - 好吗?坏的?甚至是真实的模式?

标签 c++ design-patterns

我有时会在代码中使用这种模式,我想知道它是好是坏,甚至有一个名字。我做了一些研究,看看它是否是解决问题的常用模式,但似乎找不到任何东西。它帮助我做的是防止内存的知识被太多的同事或对等对象使用。我想举个例子最能说明问题。

假设我有一个游戏,玩家有一个元素栏。库存有项目,每个项目都有一个 databaseId,因此同一项目的两个拷贝可以简单地指向同一个数据库条目。当某些东西需要从玩家的元素栏中取出元素时,他们并不知道元素本身,而只知道他们需要移除哪个元素 DB id。此外,项目由它们的 handleId(唯一)存储,用于客户端用户界面(唯一句柄传递给界面,以便 UIItem 基本上具有某种回调 ID)

伪代码:

class Inventory
    Map<int, Item> m_Items;
public:
    bool RemoveItem(int dbItemId, int count)
    {
        Item* pItem = GetItemByDBId(dbItemId);
        if (pItem) { return RemoveItem( pItem, count); }
        return false
    }
    bool RemoveItem(int handle, count)
    {
        Item* pItem = m_Items.Find(handle); //Find in my Map returns a const pointer.
        if (pItem) { return RemoveItem( pItem, count); }
        return false;
    }

private:
    bool RemoveItem(Item* item, int count); //Handles logic of removing, removes, and returns true if the remove succeeds (ie, quest items can't be removed, etc)
    Item* GetItemByHandle(int handle); //returns the item in the map by handle, null if not found
    Item* GetItemByDBId(int dbId); //returns the first item with this dbId, null if not found.

现在,如果 UI 想要删除一个项目(即,玩家将其拖入垃圾箱),那么有一个公共(public)方法可以解耦知识。如果一个 NPC 想要移除一个元素(假设 NPC 在接触玩家时偷窃,并且正在寻找一个特定的 ItemId)那么它也有一个公共(public)方法来解耦知识。

我的问题是,首先,这个模式是否有名称,或者它是我没有看到的另一个模式的变量?其次,这是好的做法还是坏的做法?对我来说,这很好,但我可能会遗漏一些东西。

最佳答案

在我看来,这是 Flyweight pattern 的相当教科书般的例子.

A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.

关于c++ - C++ 中的适配器公共(public)函数 - 好吗?坏的?甚至是真实的模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19235457/

相关文章:

c++ - 重载 C++ 模板类虚函数

c++ - 将 cout 重定向到每个线程的文件以管理线程安全日志记录

java - 将装饰器模式应用于 Java String 类

c# - 用于实现的常量字符串的最佳实践

c++ - 返回对变量 : Meaningful/useful? 的引用

c++ - 用zlib提取一个gz文件内容并保存

c++ - 特定成员的模板特化?

没有单例的 Java

c++ - 委托(delegate)应该有一个虚拟析构函数吗?

php - Doctrine2 加入 SUM