标签:
一、相关介绍
抽象工厂模式提供一个创建一系列相关或者相互依赖对象的接口,而无需指定它们具体的类。
二、UML图
三、C++程序
1 // 抽象工厂模式.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include<iostream> 6 using namespace std; 7 8 //linux系列产品 9 class linux 10 { 11 public: 12 linux(){} 13 virtual ~linux(){} 14 virtual void show_price()=0; 15 }; 16 17 //linux手机 18 class plinux :public linux 19 { 20 public : 21 plinux() 22 { 23 cout<<"i am a linux phone"<<endl; 24 } 25 virtual ~plinux(){} 26 virtual void show_price(); 27 }; 28 29 void plinux::show_price() 30 { 31 cout<<"my price is 2000"<<endl; 32 } 33 //linux电脑 34 class PClinux :public linux 35 { 36 public : 37 PClinux() 38 { 39 cout<<"i am a linux PC"<<endl; 40 } 41 virtual ~PClinux(){} 42 virtual void show_price(); 43 }; 44 void PClinux::show_price() 45 { 46 cout<<"my price is 5000"<<endl; 47 } 48 49 //windows系列产品 50 class windows 51 { 52 public: 53 windows(){} 54 virtual ~windows(){} 55 virtual void show_price()=0; 56 }; 57 58 59 //windows 手机 60 class pwindows :public windows 61 { 62 public : 63 pwindows() 64 { 65 cout<<"i am a windows phone"<<endl; 66 } 67 virtual ~pwindows(){} 68 virtual void show_price(); 69 }; 70 71 void pwindows::show_price() 72 { 73 cout<<"my price is 1999"<<endl; 74 } 75 76 //windows电脑 77 class PCwindows :public windows 78 { 79 public : 80 PCwindows() 81 { 82 cout<<"i am a windows PC"<<endl; 83 } 84 virtual ~ PCwindows(); 85 virtual void show_price(); 86 }; 87 88 void PCwindows::show_price() 89 { 90 cout<<"my price is 4999"<<endl; 91 } 92 //工厂抽象类 93 class factory 94 { 95 public: 96 factory(){} 97 virtual~factory(){} 98 virtual linux* creatlinux()=0; 99 virtual windows*creatwindows()=0; 100 }; 101 //手机工厂 102 class phonefactory:public factory 103 { 104 public: 105 phonefactory(){} 106 virtual~phonefactory(){} 107 virtual linux* creatlinux() 108 { 109 return new plinux(); 110 } 111 virtual windows* creatwindows() 112 { 113 return new pwindows(); 114 } 115 }; 116 //电脑工厂 117 class PCfactory:public factory 118 { 119 public: 120 PCfactory(){} 121 virtual~PCfactory(){} 122 virtual linux* creatlinux() 123 { 124 return new PClinux(); 125 } 126 virtual windows* creatwindows() 127 { 128 return new PCwindows(); 129 } 130 }; 131 132 //用户界面 133 int _tmain(int argc, _TCHAR* argv[]) 134 { 135 factory *phone=NULL; 136 phone=new phonefactory; 137 linux *phone_linux=phone->creatlinux(); 138 phone_linux->show_price(); 139 windows *phone_windows=phone->creatwindows(); 140 phone_windows->show_price(); 141 142 return 0; 143 }
标签:
原文地址:http://www.cnblogs.com/bewolf/p/4227979.html