Intent
Define an interface for creating an object, but let subclasses decide which class to
instantiate. Factory Method lets a class defer instantiation to subclasses.
cpp
#include <iostream>
#include <share.h>
#include <list>
#include <vector>
#include <memory>
class Document {
public:
virtual void Open() {
std::cout << "Document Open" << std::endl;
}
virtual void Close() {
}
virtual void Save() {
}
virtual void Revert() {
}
};
class MyDocument : public Document {
public:
virtual void Open() {
std::cout << "MyDocument Open" << std::endl;
}
virtual void Close() {
}
virtual void Save() {
}
virtual void Revert() {
}
};
class Application {
public:
virtual std::shared_ptr<Document> CreateDocument() {
return nullptr;
}
void NewDocument() {
std::shared_ptr<Document> doc = CreateDocument();
docs.push_back(doc);
OpenDocument(doc);
}
void OpenDocument(std::shared_ptr<Document> doc) {
doc->Open();
}
private:
std::vector<std::shared_ptr<Document> > docs{};
};
class MyApplication : public Application {
public:
virtual std::shared_ptr<Document> CreateDocument() {
std::cout << "MyApplication Construct" << std::endl;
return std::make_shared<MyDocument>();
}
};
int main()
{
std::shared_ptr<Application> app = std::make_shared<MyApplication>();
app->NewDocument();
}
Using templates to avoid subclassing
cpp
// DesignPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <share.h>
#include <list>
#include <vector>
#include <memory>
class Product {
public:
Product() {
}
virtual void callProductFunc() {
std::cout << __FUNCTION__ << std::endl;
}
};
class MyProduct1 : public Product {
public:
MyProduct1() {
}
virtual void callProductFunc() {
std::cout << __FUNCTION__ << std::endl;
}
};
class MyProduct2 : public Product {
public:
MyProduct2() {
}
virtual void callProductFunc() {
std::cout << __FUNCTION__ << std::endl;
}
};
class Creator {
public:
virtual std::shared_ptr<Product> CreateProduct() = 0;
};
// Using templates to avoid subclassing
template<class TheProduct>
class StandardCreator : public Creator {
public:
virtual std::shared_ptr<Product> CreateProduct() {
return std::make_shared<TheProduct>();
}
};
class Application {
public:
virtual void NewProduct() {
}
protected:
StandardCreator<MyProduct1> creator_1_;
StandardCreator<MyProduct2> creator_2_;
};
class MyApplication : public Application {
public:
virtual void NewProduct() {
creator_1_.CreateProduct()->callProductFunc();
creator_2_.CreateProduct()->callProductFunc();
}
};
int main()
{
std::shared_ptr<Application> app = std::make_shared<MyApplication>();
app->NewProduct();
}