#include
using namespace std;
//工厂模式:通过一个工厂模板来创建产品,常用的有线程池,消息队列,网络通信等
//抽象水果类
class AbstractFruit {
public:
virtual void showName() = 0;
};
class Apple :public AbstractFruit {
public:
void showName() {
cout << “苹果” << endl;
}
};
class Peach :public AbstractFruit {
public:
void showName() {
cout << “桃子” << endl;
}
};
//简单工厂(产品有抽象与具体层,工厂只有具体层)
class SimpleFactory {
public:
//也可以传其他类型的形参,最终需要if else或switch来判断具体类型进行生产
AbstractFruit* createFruit(string name) {
if (size(name)>0&&“apple”==name) {
return new Apple;
}
if (size(name) > 0 && “peach” == name) {
return new Peach;
}
}
};
void testSimpleFactory(){
SimpleFactory* simpleFactory = new SimpleFactory;
(simpleFactory->createFruit(“apple”))->showName();
delete simpleFactory;
simpleFactory = nullptr;
}
// 工厂方法(产品有抽象与具体层,工厂有抽象与具体层,但只能生产单一产品)
class FactoryMethod {
public:
virtual AbstractFruit* createFruit() = 0;
};
class ChinaPlace :public FactoryMethod {
public:
AbstractFruit* createFruit() {
return new Peach;
}
};
class JapanPlace :public FactoryMethod {
public:
AbstractFruit* createFruit() {
return new Apple;
}
};
void testFactoryMethod(){
FactoryMethod * factoryMethod = new ChinaPlace;
(factoryMethod->createFruit())->showName();
factoryMethod = new JapanPlace;
(factoryMethod->createFruit())->showName();
delete factoryMethod;
factoryMethod = nullptr;
}
//抽象工厂(产品有抽象与具体层,工厂有抽象与具体层,可以生产不同产品)
//抽象蔬菜类
class AbsVegetable {
public:
virtual void showName() = 0;
};
class Cucumber:public AbsVegetable {
public:
virtual void showName() {
cout << “黄瓜” << endl;
}
};
class AbstractFactory {
public:
virtual AbstractFruit* createApple() = 0;
virtual AbsVegetable* createCucumber() = 0;
};
class AmericanPlace:public AbstractFactory {
public:
AbstractFruit* createApple() {
return new Apple;
}
AbsVegetable* createCucumber() {
return new Cucumber;
}
};
void testAbstractFactory() {
AbstractFactory* abstractFactory = new AmericanPlace();
(abstractFactory->createApple())->showName();
(abstractFactory->createCucumber())->showName();
delete abstractFactory;
abstractFactory = nullptr;
}
int main() {
//测试简单工厂
/testSimpleFactory();/
//测试工厂方法
//testFactoryMethod();
//测试抽象工厂
testAbstractFactory();
return 0;
}
c++工厂模式-简单工厂,工厂方法,模板工厂
最新推荐文章于 2024-08-15 05:02:54 发布