抽象工厂模式:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。但是随着新的类型增加时,必须对原有的简单工厂进行修改,破坏了开放-封闭原则。
抽象工厂模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,抽象工厂把简单工厂的内部逻辑判断移到了客户端来进行。你想要加功能,本来是改工厂类的,而现在是修改客户端。
// AbstractFactory.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <memory> #include <iostream> using namespace std; enum LEI_FENG_TYPE { UNDER_GRADUATE, VOLUNTEER }; class LeiFeng { public: virtual void Sweep(void) = 0; virtual void Wash(void) = 0; virtual void BuyRice(void) = 0; virtual ~LeiFeng() {} }; class UnderGraduate : public LeiFeng { public: virtual void Sweep(void) { cout << "UnderGraduate Sweep !" << endl; } virtual void Wash(void) { cout << "UnderGraduate Wash !" << endl; } virtual void BuyRice(void) { cout << "UnderGraduate Buy Rice !" << endl; } }; class Volunteer :public LeiFeng { public: virtual void Sweep(void) { cout << "Volunteer Sweep !" << endl; } virtual void Wash(void) { cout << "Volunteer Wash !" << endl; } virtual void BuyRice(void) { cout << "Volunteer Buy Rice !" << endl; } }; class SimpleFactory { public: static shared_ptr<LeiFeng> CreateLeiFeng(const LEI_FENG_TYPE &type) { switch (type) { case UNDER_GRADUATE: cout << "Create undergraduate:" << endl; return make_shared<UnderGraduate>(); case VOLUNTEER: cout << "Create volunteer:" << endl; return make_shared<Volunteer>(); default: cout << "Error Type" << endl; return nullptr; } } }; class AbstractFactory { public: virtual shared_ptr<LeiFeng> CreateLeiFeng() = 0; }; class UnderGraduateFactory : public AbstractFactory { public: shared_ptr<LeiFeng> CreateLeiFeng() { return make_shared<UnderGraduate>(); } }; class VolunteerFactory : public AbstractFactory { public: shared_ptr<LeiFeng> CreateLeiFeng() { return make_shared<Volunteer>(); } }; int main() { //1.simple factory类型判断放在工厂类中 auto lei_feng_a = SimpleFactory::CreateLeiFeng(UNDER_GRADUATE); lei_feng_a->Sweep(); lei_feng_a->Wash(); lei_feng_a->BuyRice(); //2.abstract factory类型判断是由不同的继承来实现 auto abstract_factory = make_shared<UnderGraduateFactory>(); auto lei_feng_b = abstract_factory->CreateLeiFeng(); lei_feng_b->Sweep(); lei_feng_b->Wash(); lei_feng_b->BuyRice(); return 0; }