工厂模式在于把各个具体产品的创建延迟到每个具体的工厂来负责创建和初始化
在客户端的修改只需要改动具体用哪种工厂就可以,其他关注的都是抽象类
工厂模式的优点:
1.低耦合性
把各个具体产品的创建延迟到每个具体的工厂来负责创建和初始化
2.更符合开放-封闭原则
对于修改,只需要在自己的类中修改;对于扩展,只需要新增工厂类、产品类
缺点:
类的大量增加
抽象工厂:
即抽象工厂关联抽象类,
客户端所能涉及到的全是抽象接口
#pragma once
#include <iostream>
#include <string>
using namespace std;
class P
{
public:
P()
{
cout << "P Coustruction" << endl;
}
virtual void DoSomething()
{
cout << "P DoSomething" << endl;
}
};
class P1 :public P {
public:
P1(int a, int b) :P(),A(a),B(b)
{
cout << "P1 Coustruction" << endl;
}
virtual void DoSomething() override
{
printf("P1 DoSomething a = %d, b = %d\n",A,B);
}
int A, B;
};
class P2 : public P {
public:
P2(string name, string id) :P(),Name(name),Id(id)
{
cout << "P2 Coustruction" << endl;
}
virtual void DoSomething() override
{
printf("P2 DoSomething Name = %s, Id = %s\n", Name.c_str(), Id.c_str());
}
string Name, Id;
};
//抽象工程接口
class IFactoryInterface
{
public:
//
virtual P* CreateProduct() = 0;
};
class FactoryA :public IFactoryInterface
{
public:
FactoryA()
{
cout << "FactoryA Coustruction" << endl;
}
virtual P* CreateProduct() override
{
//工厂模式在创建对应实例的时候, 很好的隐藏了配置细节,将复杂且不同的初始化配置,推迟到各个具体的工厂去
return new P1(1,2);
}
};
class FactoryB :public IFactoryInterface
{
public:
FactoryB()
{
cout << "Factoryb Coustruction" << endl;
}
virtual P* CreateProduct() override
{
return new P2("cjc", "male");
}
};
void TestFactory()
{
IFactoryInterface* factoryA = new FactoryA();
P* pA= factoryA->CreateProduct();
pA->DoSomething();
IFactoryInterface* factoryB= new FactoryB();
P* pB = factoryB->CreateProduct();
pB->DoSomething();
}