
1.3、抽象工厂模式
抽象工厂模式提供创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
当存在多个产品系列,而客户端只使用一个系列的产品时,可以考虑使用抽象工厂模式。
缺点:当增加一个新系列的产品时,不仅需要现实具体的产品类,还需要增加一个新的创建接口,扩展相对困难。
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 111
|
#include "stdafx.h" #include <iostream>
using namespace std;
class coat { public: virtual const string& color() = 0; };
class whitecoat :public coat { private: string str_color; public: whitecoat() :coat(), str_color("white coat") {} const string& color() { cout << str_color.data() << endl; return str_color; } };
class blackcoat :public coat { private: string str_color; public: blackcoat() :coat(), str_color("black coat") {} const string& color() { cout << str_color.data() << endl; return str_color; } };
class pant { public: virtual const string& color() = 0; };
class whitepant :public pant { private: string str_color; public: whitepant() :pant(), str_color("white pant") {} const string& color() { cout << str_color.data() << endl; return str_color; } };
class blackpant :public pant { private: string str_color; public: blackpant() :pant(), str_color("black pant") {} const string& color() { cout << str_color.data() << endl; return str_color; } };
class factory { public: virtual coat* createcoat() = 0; virtual pant* createpant() = 0; }; class whitefactory :public factory { public: coat* createcoat() { return new whitecoat(); } pant* createpant() { return new whitepant(); } }; class blackfactory :public factory { public: coat* createcoat() { return new blackcoat(); } pant* createpant() { return new blackpant(); } };
int main() { whitefactory wf; wf.createcoat()->color(); wf.createpant()->color(); blackfactory bf; bf.createcoat()->color(); bf.createpant()->color(); cin.get(); return 0; }
|
近期评论