C++策略设计模式,制作一个接口数组

C++ Strategy Design Pattern, making an interface array

本文关键字:一个 接口 数组 设计模式 策略 C++      更新时间:2023-10-16

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

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

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

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

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

errr,例如。。。std::vector<boost::shared_ptr<抽象策略>>

使用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());
}

看起来很好,很优雅,加上你得到了经过良好测试的代码,可以将你的值视为对象,而不是指针

注意:这些函数名称提供了信息,但您可以使用重写来拥有单个接口。