一个工厂函数模板
// 例子,总有一些基类希望在初始化时调用派生类的虚函数实现,但是在基类的构造和析构时调用非常不好,最好提供工厂函数来实现
class B {
public:
B() {
/* ... */
f(); // BAD: C.82: Don't call virtual functions in constructors and destructors
/* ... */
}
virtual void f() = 0;
};
class B {
protected:
class Token {};
public:
explicit B(Token) { /* ... */ } // create an imperfectly initialized object
virtual void f() = 0;
template<class T>
static shared_ptr<T> create() // interface for creating shared objects
{
auto p = make_shared<T>(typename T::Token{});
p->post_initialize();
return p;
}
protected:
virtual void post_initialize() // called right after construction
{ /* ... */ f(); /* ... */ } // GOOD: virtual dispatch is safe
};
class D : public B { // some derived class
protected:
class Token {};
public:
explicit D(Token) : B{ B::Token{} } {}
void f() override { /* ... */ };
protected:
template<class T>
friend shared_ptr<T> B::create();
};
shared_ptr<D> p = D::create<D>(); // creating a D object
class Factory {
public:
template<class T>
static T* CreateProduct() {
return new T();
}
};
class Product {
public:
virtual ~Product() = default;
virtual void Use() = 0;
};
class ProductA : public Product {
public:
virtual ~ProductA() override = default;
void Use() override {
std::cout << "ProductA" << std::endl;
}
private:
ProductA() = default; // 构造函数私有,ProductA就不能随意实例化
template<class T>
friend T* Factory::CreateProduct(); // 友元函数,可以访问ProductA的私有成员
};