- /*
- 简单工厂模式:跟工厂模式很类似,不过在函数里面加上了逻辑判断
- Created by Phoenix_FuliMa
- */
- #include <iostream>
- using namespace std;
- class Product
- {
- public:
- virtual void display() = 0;
- };
- class Product1:public Product
- {
- public:
- void display()
- {
- cout<<"I am product1..."<<endl;
- }
- };
- class Product2:public Product
- {
- public:
- void display()
- {
- cout<<"I am product2..."<<endl;
- }
- };
- class Factory
- {
- public:
- Product *CreateProduct(const char *type)
- {
- if(strcmp(type, "product1") == 0)
- {
- return new Product1;
- }
- else if(strcmp(type, "product2") == 0)
- {
- return new Product2;
- }
- else
- {
- return NULL;
- }
- }
- };
- int main()
- {
- Factory *fac = new Factory();
- Product *product1 = fac->CreateProduct("product1");
- Product *product2 = fac->CreateProduct("product2");
- product1->display();
- product2->display();
- system("pause");
- return 0;
- }
05-22
05-22
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交