简单工厂模式

发布时间 2023-04-26 18:38:00作者: 泽良_小涛

一、第一种方法

//实现了客户端调用和implOne,implTwo的解耦合
//factory类实现了变化隔离

 1 #include<string>
 2 #include "DynOBJ.h"
 3 using namespace std;
 4 
 5 class Api {
 6 public:
 7     virtual void test(string s) = 0;
 8 protected:
 9     Api(){}
10 };
11 
12 
13 class ImpleOne :public Api {
14 public:
15     void test(string s) {
16         cout << "现在是One在执行" << s;
17     }
18 };
19 
20 class ImpleTwo :public Api {
21 public:
22     void test(string s) {
23         cout << "现在是Two在执行" << s;
24     }
25 };
26 
27 class Factory {
28 public:
29     static Api* createApi(int type) {
30 
31         Api* pApi = nullptr;
32         if (type == 1) {
33             pApi = new ImpleOne();
34         }
35         if (type == 2) {
36             pApi = new ImpleTwo();
37         }
38         return pApi;
39     }
40 
41     static Api* createApi() {
42         return new ImpleOne();
43     }
44 };
45 
46 
47 /**
48 传入参数1,可以实现从数据库读入的功能
49 传入参数2,可以实现从文本文件读入的功能
50 */
51 int main(void) {
52     Api* pApi = Factory::createApi(2);//客户端,还是知道工厂的细节
53 
54     pApi->test("--现在是使用简单工厂方法重构\r\n");
55     Api* pApiEx = Factory::createApi();
56     system("pause");
57     return 0;
58 }
59 //实现了客户端调用和implOne,implTwo的解耦合
60 //factory类实现了变化隔离
View Code