为什么要工厂模式
工厂模式封装了对象的创建,不封装就需要new来new去。项目中类名比较多时,需要实例化对象比较多,此时需要new对象时就需要记住很多的类名,当类名需要改变时调用的地方也需要改来改去。
因此添加工厂模式,用户需要什么样的对象工厂就返回一个什么样的对象
简单工厂实现
#include<iostream>
#include<string>
using namespace std;
class Car
{
public:
Car(string n):name(n){}
virtual void show() = 0;
protected:
string name;
};
class Bmw :public Car
{
public:
Bmw(string s) :Car(s) {}
void show()
{
cout << "获取了一辆宝马汽车 " << name << endl;
}
};
class Audi :public Car
{
public:
Audi(string s) :Car(s) {}
void show()
{
cout << "获取了一辆奥迪汽车 " << name << endl;
}
};
enum CarType
{
BWM,
AUDI
};
class SimpleFactory
{
public:
Car* createCar(CarType ct)
{
switch (ct)
{
case BWM:
return new Bmw("X1");
case AUDI:
return new Audi("A6");
default:
cerr << "传入汽车类型不正确" << endl;
break;
}
return nullptr;
}
};
int main()
{
/*Car* c1 = new Bmw("X1");//相当于用户要一个对象(宝马X1),用户还需要宝马怎么造,但用户根本不关心怎么造
c1->show();
Car* c2 = new Audi("A6");
c2->show();*/
SimpleFactory* factory = new SimpleFactory();
Car* p1 = factory->createCar(BWM);
p1->show();
return 0;
}
简单工厂的缺点
同一个工厂不可能又建宝马,又建奥迪。实际应该是俩个工厂。其次简单工厂的设计不封闭,需要增加对象就需要重写createCar()接口
工厂模式代码实现
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Car
{
public:
Car(string n):name(n){}
virtual void show() = 0;
protected:
string name;
};
class Bmw :public Car
{
public:
Bmw(string s) :Car(s) {}
void show()
{
cout << "获取了一辆宝马汽车 " << name << endl;
}
};
class Audi :public Car
{
public:
Audi(string s) :Car(s) {}
void show()
{
cout << "获取了一辆奥迪汽车 " << name << endl;
}
};
class Factory
{
public:
virtual Car* createCar(const string name) = 0;
};
class BmwFactory :public Factory
{
public:
Car* createCar(const string name)
{
return new Bmw(name);
}
};
class AudiFactory :public Factory
{
public:
Car* createCar(const string name)
{
return new Audi(name);
}
};
int main()
{
unique_ptr<Factory> f1 (new BmwFactory());
Car* c1 = f1->createCar("X1");
c1->show();
unique_ptr<Factory> f2(new AudiFactory());
Car* c2 = f2->createCar("A8");
c2->show();
return 0;
}
完美解决了软件设计的开闭原则。已有的代码封闭不动,想要添加新功能只需要增加相应的派生类