标签:
1.意图
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使一个类的实例化延迟到其子类。
2.动机
框架使用抽象类定义和维护对象之间的关系。这些对象的创建通常也由框架负责。
3.适用性
4.结构
5.代码实例
class Product
{
public:
virtual ~Product() = 0;
};
class OneProduct : public Product
{
public:
OneProduct();
};
class TwoProduct : public Product
{
public:
TwoProduct();
};
class ThreeProduct : public Product
{
public:
ThreeProduct();
};
class FourProduct : public Product
{
public:
FourProduct();
};
#include <memory>
class Product;
class Creator
{
public:
virtual std::shared_ptr<Product> FactoryMethod() = 0;
};
class OneCreator : public Creator
{
public:
std::shared_ptr<Product> FactoryMethod();
};
class TwoCreator : public Creator
{
public:
std::shared_ptr<Product> FactoryMethod();
};
class ThreeCreator : public Creator
{
public:
std::shared_ptr<Product> FactoryMethod();
};
class FourCreator : public Creator
{
public:
std::shared_ptr<Product> FactoryMethod();
};
#include "Product.h"
#include <iostream>
Product::~Product()
{
}
OneProduct::OneProduct()
{
std::cout << "OneProduct Created" << std::endl;
}
TwoProduct::TwoProduct()
{
std::cout << "TwoProduct Created" << std::endl;
}
ThreeProduct::ThreeProduct()
{
std::cout << "ThreeProduct Created" << std::endl;
}
FourProduct::FourProduct()
{
std::cout << "FourProduct Created" << std::endl;
}
#include "Creator.h"
#include "Product.h"
std::shared_ptr<Product> OneCreator::FactoryMethod()
{
auto pProduct = std::shared_ptr<Product>(new OneProduct());
return pProduct;
}
std::shared_ptr<Product> TwoCreator::FactoryMethod()
{
auto pProduct = std::shared_ptr<Product>(new TwoProduct());
return pProduct;
}
std::shared_ptr<Product> ThreeCreator::FactoryMethod()
{
auto pProduct = std::shared_ptr<Product>(new ThreeProduct());
return pProduct;
}
std::shared_ptr<Product> FourCreator::FactoryMethod()
{
auto pProduct = std::shared_ptr<Product>(new FourProduct());
return pProduct;
}
#include<memory>
#include"Creator.h"
int main()
{
auto pOneCreator = std::shared_ptr<OneCreator>(new OneCreator());
auto pOneProduct = pOneCreator->FactoryMethod();
auto pTwoCreator = std::shared_ptr<TwoCreator>(new TwoCreator());
auto pTwoProduct = pTwoCreator->FactoryMethod();
auto pThreeCreator = std::shared_ptr<ThreeCreator>(new ThreeCreator());
auto pThreeProduct = pThreeCreator->FactoryMethod();
auto pFourCreator = std::shared_ptr<FourCreator>(new FourCreator());
auto pFourProduct = pFourCreator->FactoryMethod();
while(1);
}
6.测试结果
7.效果
8.变形
工厂方法的变形是:可以参数化工厂方法,以使工厂方法可以创建多种产品。
标签:
原文地址:http://www.cnblogs.com/mgp200866130/p/5463698.html