C++进阶系列之设计模式(1)---设计模式的核心思想
就是实实在在的构造一个工厂类(高內聚,新增添的话,必须修改原有代码,而不是扩充原有代码),不易扩充;
作用:用一个类去创建其它类,但都有一个接口(面向抽象类编程);
#include<iostream>
#include<string.h>
using namespace std;
class Fruit{
public:
virtual void getFruit() = 0;
private:
};
class Banana : public Fruit{
public:
virtual void getFruit(){
cout<<"我是香蕉......"<<endl;
}
private:
};
class Apple : public Fruit{
public:
virtual void getFruit(){
cout<<"我是苹果......"<<endl;
}
private:
};
class Factory{
public:
Fruit *create(const char *p){
if(strcmp(p, "banana") == 0){
return new Banana;
}else if(strcmp(p, "apple") == 0){
return new Apple;
}else{
cout<<"不支持"<<endl;
}
}
private:
};
int main(void){
Factory *f = new Factory;
Fruit *fruit = NULL;
//工厂生产香蕉
fruit = f->create("banana");
fruit->getFruit();
//工厂生产苹果
fruit = f->create("apple");
fruit->getFruit();
delete f;
return 0;
}
推荐阅读: