抽象工厂模式
其实这部分内容没啥好讲的把代码看懂就行了,原理都不难,就比如本例子,一个工厂既可以生成鼠标和键盘,至于怎么生成就是工厂的事情了,比如联想工厂和戴尔工厂,对于用户来说,我想用哪个牌子的鼠标和键盘这是我自己可以选择的。
#include<iostream>
using namespace std;
class keyboard{
public:
virtual void getKeyBoard() = 0;
};
class keyboardDell :public keyboard{
public:
virtual void getKeyBoard() override final
{
cout << "我是戴尔的键盘\n";
}
};
class keyboardLenovo :public keyboard{
public:
virtual void getKeyBoard() override final
{
cout << "我是联想的键盘\n";
}
};
class mouse{
public:
virtual void getMouse() = 0;
};
class mouseDell :public mouse
{
public:
virtual void getMouse() override final
{
cout << "我是戴尔的鼠标\n";
}
};
class mouseLenovo :public mouse
{
public:
virtual void getMouse() override final
{
cout << "我是联想的鼠标\n";
}
};
class Factory{
public:
virtual keyboard *CreateKeyBoard() = 0;
virtual mouse *CreateMouse() = 0;
};
class DellFactory:public Factory
{
public:
virtual keyboard *CreateKeyBoard() override final
{
return new keyboardDell;
}
virtual mouse *CreateMouse() override final
{
return new mouseDell;
}
};
class LenovoFactory :public Factory
{
public:
virtual keyboard *CreateKeyBoard() override final
{
return new keyboardLenovo;
}
virtual mouse *CreateMouse() override final
{
return new mouseLenovo;
}
};
void main()
{
//我想用联想的键盘和戴尔的鼠标
Factory *m_lenf = new LenovoFactory;
keyboard *m_lenkey = m_lenf->CreateKeyBoard();
m_lenkey->getKeyBoard();
Factory *m_dellf = new DellFactory;
mouse *m_dellmouse = m_dellf->CreateMouse();
m_dellmouse->getMouse();
system("pause");
}
结果:
案例二:
抽象工厂模式是按照产品族来生产产品(产地相同的用一个工厂来生产)—一个地点有一个工厂,该工厂负责生产本产地的所有产品。
抽象工厂一般用在大型项目中。
案例三:部件相关