簡單工廠模式 - 優(yōu)缺點(diǎn)
模式的核心是工廠類,這個類負(fù)責(zé)產(chǎn)品的創(chuàng)建,而客戶端可以免去產(chǎn)品創(chuàng)建的責(zé)任,這實(shí)現(xiàn)了責(zé)任的分割。但由于工廠類集中了所有產(chǎn)品創(chuàng)建邏輯的,如果不能正常工作的話會對系統(tǒng)造成很大的影響。如果增加新產(chǎn)品必須修改工廠角色的源碼
//filename factory.h
#include <iostream>
#include <string>
class Car
{
public:
std::string Drive();
virtual std::string Stop() = 0;
};
class RedCar :public Car
{
public:
std::string Drive() {
return "RedCar is Drived";
}
std::string Stop() {
return "RedCar is Stoped";
}
} ;
class BlueCar :public Car
{ //一定要從寫父類,使用override
public:
std::string Drive() {
return "BlueCar is Drived";
}
std::string Stop() {
return "BlueCar is Stop";
}
} ;
//工廠類,來構(gòu)造其實(shí)例
class CarFactory
{
//依賴類Car
public:
Car *Create(std::string CarType) {
if(CarType == "red") {
return new RedCar();
} else if(CarType == "blue" ) {
return new BlueCar();
} else
return nullptr;
}
};
使用實(shí)例:
#include "factory.h"
int main(){
CarFactory *carF = new CarFactory();
Car *car = carF->Create("red");//實(shí)例哪個類
return 0;
}