首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在工厂中管理类实例的更好方法是什么?

在工厂中管理类实例的更好方法是什么?
EN

Stack Overflow用户
提问于 2012-03-06 20:58:15
回答 2查看 128关注 0票数 0

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

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

因此,我编写了一个方法,在第一次请求时分配一个Currency,否则返回一个现有的Currency

代码语言:javascript
复制
    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成员,因为没有定义默认构造函数:

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

我不想在Currency类中保存CcyPair指针。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-06 21:17:49

我知道你说过你不想保存指向货币对象的指针,但是你对持有引用有什么感觉呢?我不确定您是否希望避免指针,这样您就不会承受大量空检查的负担,或者您是否有其他原因。下面是一个使用引用的CcyPair示例:

代码语言:javascript
复制
  class CcyPair
      {
      public:
        CcyPair(const Currency& ccy1, const Currency& ccy2) 
          : _ccy1(ccy1), _ccy2(ccy2) {}

        CcyPair(const std::string& ccyName1, const std::string& ccyName2) 
          : _ccy1(Currency::getCcy(ccyName1)), _ccy2(Currency::getCcy(ccyName2)) {}

      private:
        // need to make these const since getCcy returns const 
        // you could also change the signature of getCcy to return non-const
        const Currency & _ccy1;
        const Currency & _ccy2;
      };
票数 1
EN

Stack Overflow用户

发布于 2012-03-06 21:02:51

你要找的是飞度模式。读取http://en.wikipedia.org/wiki/Flyweight_pattern

顺便说一句,在飞重方面,您也可以有一个关联的状态,但是必须将该状态过滤到一个单独的类中。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9591799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档