gpt4 book ai didi

c++ - 在工厂内管理类实例的更好方法是什么?

转载 作者:行者123 更新时间:2023-11-27 23:25:51 25 4
gpt4 key购买 nike

我在 C++ 项目中遇到“设计”问题。

我有一个类,名为 Currency(可以是 "USD""EUR" 等等...,并得到了一些方法)项目中到处都有这个类 new-ed 的实例,但只能有一堆不同的货币(~100)。

所以我写了一个方法,它在第一次被询问时分配一个 Currency,然后返回一个现有的 Currency 否则:

    class Currency 
{
public:
typedef std::map<std::string, Currency*> CurrencyMap_t;
public:
static CurrencyMap_t _currencies;

public:
static const Currency& getCcy(const std::string& name)
{
CurrencyMap_t::const_iterator it(_currencies.find(name));

if (it == _currencies.end())
it = _currencies.insert(std::make_pair(name, new Currency(name))).first;

return *(it->second);
}

private:
// can't instantiate from outside
Currency();
Currency(const Currency& other);
private:
// private ctor
explicit Currency(const std::string& name) {... }
};

所以,现在,每种不同的 Currency 我只有一个实例。

但是,我不能再有一个包含 Currency 成员的类,因为没有定义默认构造函数:

    class CcyPair
{
public:
CcyPair(const Currency& ccy1, const Currency& ccy2) {}
private:
Currency _ccy1; // won't compile because "no default-constructor available"
Currency _ccy2;
};

而且我不想在 CcyPair 类中保留 Currency 指针。

你有没有更好的方法来实现这样一个“模式”,确保如果一个类的两个实例(这里是 Currency 类)有相同的属性,那么它实际上是 相同实例(相同的底层引用)?

最佳答案

您正在寻找的是享元模式。阅读http://en.wikipedia.org/wiki/Flyweight_pattern

顺便说一句,使用享元你也可以关联一个状态,但必须将该状态过滤到一个单独的类中。

关于c++ - 在工厂内管理类实例的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9591799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com