简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。
就像你的计算器,让客户端不用管那个类的实例,只需要把‘+’给工厂,工厂自动就给出了相应的实例,客户端只要去做运算就可以了,不同的实例会实现不同的运算。
工厂方法模式,定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法是一个类的实例化延迟到其子类。
UML图如下:
适用性:
----当一个类不知道它所必须创建的对象的类的时候。
----当一个类希望由它的子类来之指定它所创建的对象的时候
----当类将创建对象的职责委托给多个帮组子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
参与者:
Product
----定义工厂方法所创建的对象的接口
ConcreteProduct
----实现Product接口
Creator
----声明工厂方法,该方法返回一个Product类型的对象。Creator也可以定义一个工厂方法的缺省实现,它返回一个缺省实现,它返回一个缺省的ConcreteProduct对象
----可以调用工厂方法以创建一个Product对象
ConcreteCreator
----重定义工厂方法以返回一个ConcreteProduct实例。
工厂方法模式实现时,客户端需要决定实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂的内部逻辑判断移到了客户端代码来进行。你想呀加功能,本来是改工厂类的,而现在是修改客户端类。
现在我们来看看程序的具体实现:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
#include <iostream>
using namespace std; class LeiFeng { public: virtual void Sweep() { cout << "扫地" << endl; } virtual void Wash() { cout << "洗衣" << endl; } virtual void BuyRice() { cout << "买米" << endl; } }; class Undergraduate : public LeiFeng { public: void Sweep() { cout << "大学生"; LeiFeng::Sweep(); } void Wash() { cout << "大学生"; LeiFeng::Wash(); } void BuyRice() { cout << "大学生"; LeiFeng::BuyRice(); } }; class Volunteer : public LeiFeng { public: void Sweep() { cout << "志愿者"; LeiFeng::Sweep(); } void Wash() { cout << "志愿者"; LeiFeng::Wash(); } void BuyRice() { cout << "志愿者"; LeiFeng::BuyRice(); } }; //工厂抽象类 class Factory { public: virtual LeiFeng *CreateLeiFeng() = 0; }; //具体的大学生工厂 class UndergraduateFactory : public Factory { public: LeiFeng *CreateLeiFeng() { return new Undergraduate(); } }; //具体的志愿者工厂 class VolunteerFactory : public Factory { public: LeiFeng *CreateLeiFeng() { return new Volunteer(); } }; int main() { Factory *p_factory = new UndergraduateFactory(); LeiFeng *p_student = p_factory->CreateLeiFeng(); p_student->Sweep(); p_student->Wash(); p_student->BuyRice(); delete p_factory; p_factory = NULL; p_factory = new VolunteerFactory(); delete p_student; p_student = NULL; p_student = p_factory->CreateLeiFeng(); p_student->Sweep(); p_student->Wash(); p_student->BuyRice(); delete p_factory; p_factory = NULL; delete p_student; p_student = NULL; return 0; } |