首先看簡單工廠模式
此模式的職責就是負責創建其他類的的實例,通常是一類對象
如下fruit -> banana fruit -> apple
#include <iostream>
using namespace std;
class Fruit
{
public:
virtual void getFruit() = 0;
};
class banana: public Fruit
{
public:
virtual void getFruit()
{
cout << "banana" <<endl;
}
};
class Apple : public Fruit
{
public:
virtual void getFruit()
{
cout << "apple" << endl;
}
};
class Factory
{
public:
Fruit* create_fruit(char* s) //每增加一種類型 都需要 修改這裏的代碼 不符合開閉原則
{
if (strcmp(s, "banana") == 0)
{
return new banana();
}
else if (strcmp(s, "apple") == 0)
{
return new Apple();
}
else{
return NULL;
}
}
};
int main()
{
Factory* f = new Factory();
Fruit* fruit = f->create_fruit("banana");
fruit->getFruit();
delete fruit;
fruit = f->create_fruit("apple");
fruit->getFruit();
delete fruit;
system("pause");
return 0;
}
缺點 就是 當有更多種類的水果時,都需要修改工廠類的源代碼 (但是簡單易實現)
再看看 真正的工廠
#include <iostream>
using namespace std;
class Fruit
{
public:
virtual void getFruit() = 0;
};
class Banana : public Fruit
{
public:
virtual void getFruit()
{
cout << "banana" << endl;
}
};
class Apple : public Fruit
{
public:
virtual void getFruit()
{
cout << "apple" << endl;
}
};
class abs_Factory //這是一個抽象的工廠
{
public:
virtual Fruit* create_product() = 0;
};
class Banana_Factory:public abs_Factory //這是一個生產banana的工廠
{
public:
virtual Fruit* create_product()
{
return new Banana;
}
};
//通過增加代碼 來實現功能增強 符合開閉原則
class Apple_Factory :public abs_Factory //這是一個生產apple的工廠
{
public:
virtual Fruit* create_product()
{
return new Apple;
}
};
//如果還需要什麼水果 ,通過增加 代碼
// 先創建一種水果 fruit->truth_fruit
// 再創建一種生產這種水果的工廠 abs_factory-> ctreat_thruth_fruit
// 開始愉快的生產水果
int main()
{
abs_Factory *factory =NULL;
Fruit* fruit = NULL;
factory = new Banana_Factory;
fruit = factory->create_product();
fruit->getFruit();
factory = new Apple_Factory;
fruit = factory->create_product();
fruit->getFruit();
delete factory;
delete fruit;
system("pause");
return 0;
}
從這裏,就可以看出一點面向接口編程的味道了,因爲有這個抽象factory在,所以任何水果都可以生產出來,而且是一致的生產
如果一層抽象解決不了問題,那就在增加一層!