4

在实现了策略模式之后,我想创建一个接口类型的数组,然后我可以向其中添加任何具体类型。

对于那些不知道策略模式的人: http ://en.wikipedia.org/wiki/Strategy_pattern 在这个特定的例子中,我想做一个 StrategyInterface 数组,然后我可以用具体类型的 A、B 和 C 填充. 但是,因为这是一个抽象类,我无法完成它。有没有办法做到这一点,或者完全不可能,而不删除抽象方法?

4

4 回答 4

6

使数组存储指向接口类型的指针:

typedef std::vector<Interface *> Array;
Array myArray;
myArray.push_back(new A());

此外,您可以使用 ptr_vector 为您管理内存:

typedef boost::ptr_vector<Interface> Array;
// the rest is the same
于 2008-10-05T07:03:31.653 回答
2

存储指针而不是对象.....如果要存储对象,请使用 boost::shared_ptr 。

于 2008-10-05T06:59:38.400 回答
1

错误,例如... std::vector< boost::shared_ptr< AbstractStrategy >>

于 2008-10-05T07:04:26.537 回答
1

使用 boost any 怎么样?

这是它的外观示例

#include <list>
#include <boost/any.hpp>

using boost::any_cast;
typedef std::list<boost::any> many;

void append_int(many & values, int value)
{
   boost::any to_append = value;
   values.push_back(to_append);
}

void append_string(many & values, const std::string & value)
{
   values.push_back(value);
}

void append_char_ptr(many & values, const char * value)
{
   values.push_back(value);
}

void append_any(many & values, const boost::any & value)
{
   values.push_back(value);
}

void append_nothing(many & values)
{
   values.push_back(boost::any());
}

看起来不错且优雅,而且您获得了经过良好测试的代码,并且可以将您的值视为对象而不是指针

注意:这些函数名称是信息性的,但您可以使用覆盖来获得单个接口。

于 2008-10-05T08:19:29.147 回答