//缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。
#include <iostream>
#include <string>
using namespace std;
class Cost{
public:
virtual const string& color() = 0;
};
class WhiteShit : public Cost{
public:
WhiteShit():Cost(),m_color("white"){}
const string& color(){
cout << m_color << endl;
return m_color;
}
private:
string m_color;
};
class BlackShit : public Cost{
public:
BlackShit():Cost(),m_color("black"){}
const string& color(){
cout << m_color << endl;
return m_color;
}
private:
string m_color;
};
class Plant{
public:
virtual const string& color() = 0;
};
class WhitePlant : public Plant{
public:
WhitePlant():Plant(),m_color("white"){}
const string& color(){
cout << m_color << endl;
return m_color;
}
private:
string m_color;
};
class BlackPlant : public Plant{
public:
BlackPlant():Plant(),m_color("black"){}
const string& color(){
cout << m_color << endl;
return m_color;
}
private:
string m_color;
};
class Factory{
public:
virtual Cost *createCost() = 0;
virtual Plant *createPlant() = 0;
};
class WhiteFactory : public Factory{
public:
Cost *createCost() override{
return new WhiteShit();
}
Plant *createPlant() override{
return new WhitePlant();
}
};
class BlackFactory : public Factory{
public:
Cost *createCost() override{
return new BlackShit();
}
Plant *createPlant() override{
return new BlackPlant();
}
};
int main()
{
WhiteFactory factory;
factory.createCost()->color();
factory.createPlant()->color();
BlackFactory factory1;
factory1.createCost()->color();
factory1.createPlant()->color();
cout << "Hello, world!" << endl;
return 0;
}
参考:https://www.cnblogs.com/chengjundu/p/8473564.html