我有一个具有2个纯虚拟方法的类和需要使用此类对象的另一个类。我想让这个类的用户指定应该在哪个派生类中使用抽象类。 我正在努力弄清楚正确的方法。在另一个类中使用抽象类对象的C++设计模式
struct abstract {
virtual int fst_func() = 0;
virtual void sec_func(int) = 0;
};
// store an instance of "abstract".
class user_of_abstract
{
private:
abstract* m_abstract;
public:
// Pass a pointer to an "abstract" object. The caller takes care of the memory resource.
user_of_abstract_base(abstract* a) : m_abstract(a) { }
// Pase any type, which needs to be derived from "abstract" and create a copy. Free memory in destructor.
template<class abstract_type>
user_of_abstract_base(abstract_type const& a) : m_abstract(new abstract_type(a)) { }
// use the stored member to call fst_func.
int use_fst_func() {
return this->m_abstract->fst_func();
}
// use the stored member to call sec_func.
void use_sec_func(int x) {
this->m_abstract->sec_func(x);
}
};
// use boost::shared_ptr
class user_of_abstract
{
private:
boost::shared_ptr<abstract> m_abstract;
public:
// Pass a pointer to an "abstract" object. The caller takes care of the memory resource.
user_of_abstract_base(boost::shared_ptr<abstract> a) : m_abstract(a) { }
// use the stored member to call fst_func.
int use_fst_func() {
return this->m_abstract->fst_func();
}
// use the stored member to call sec_func.
void use_sec_func(int x) {
this->m_abstract->sec_func(x);
}
};
// pass a pointer of an "abstract" object wherever needed.
struct user_of_abstract
{
// use the passed pointer to an "abstract" object to call fst_func.
int use_fst_func(abstract* a) {
return a->fst_func();
}
// use the passed pointer to an "abstract" object to call sec_func.
void use_sec_func(abstract* a, int x) {
a->sec_func(x);
}
};
要注意从sec_func该参数的“X”()是很重要的必须是同一个“抽象”的实例()由fst_func返回的值。
编辑: 增加了另一种方法使用boost :: shared_ptr应该采取最大的优势。
我认为你的第二类的名字应该是'user_of_abstract_base'。 – 2011-06-13 05:50:42
不要忘了你需要一个虚拟的析构函数来抽象! – 2011-06-13 05:56:20
@Billy |是的,谢谢你的提示。我已经缩短了相关部分的代码。 – 0xbadf00d 2011-06-13 06:06:43