my设计模式:抽象工厂模式
【摘要】 用小代码直观了解设计模式
#include <iostream>
using namespace std;
/*抽象工厂类例子*/
/*冰箱产品*/
class FridgeInterface
{
public:
FridgeInterface(){}
virtual ~FridgeInterface(){}
virtual void Install() = 0;
};
class HaierFridge : public FridgeInterface
{
public:
HaierFridge(){}
void Install(){cout<<"Install Haier Fridge.."<<endl;}
};
class MiDeaFridge : public FridgeInterface
{
public:
MiDeaFridge(){}
void Install(){cout<<"Install MiDea Fridge.."<<endl;}
};
/*电视产品*/
class TelevisionInterface
{
public:
TelevisionInterface(){}
virtual ~TelevisionInterface(){}
virtual void Install() = 0;
};
class HaierTelevision : public TelevisionInterface
{
public:
HaierTelevision(){}
void Install(){cout<<"Install Haier Television.."<<endl;}
};
class MideaTelevision : public TelevisionInterface
{
public:
MideaTelevision(){}
void Install(){cout<<"Install MiDea Television.."<<endl;}
};
/*智能品牌家具: 家具统一使用同一品牌产品(一套家具只包含电视和冰箱)*/
class SmartHomeInterface
{
public:
SmartHomeInterface(){}
virtual ~SmartHomeInterface(){}
virtual FridgeInterface *CreateFridge()=0;
virtual TelevisionInterface *CreateTelevision()=0;
};
class HaierSmartHome : public SmartHomeInterface
{
public:
HaierSmartHome(){};
FridgeInterface *CreateFridge(){return new HaierFridge;}
TelevisionInterface *CreateTelevision(){return new HaierTelevision;}
};
class MiDeaSmartHome : public SmartHomeInterface
{
public:
MiDeaSmartHome(){};
FridgeInterface *CreateFridge(){return new MiDeaFridge;}
TelevisionInterface *CreateTelevision(){return new MideaTelevision;}
};
/*扩展奥克斯家具:产品等级扩展容易*/
class AUXFrige : public FridgeInterface
{
public:
AUXFrige(){};
void Install(){cout<<"Install AUX Fridge.."<<endl;}
};
class AUXTelevision : public TelevisionInterface
{
public:
AUXTelevision(){}
void Install(){cout<<"Install AUX Television.."<<endl;}
};
class AUXSmartHome : public SmartHomeInterface
{
public:
AUXSmartHome(){}
FridgeInterface *CreateFridge(){return new AUXFrige;}
TelevisionInterface *CreateTelevision(){return new AUXTelevision;}
};
/*扩展各厂家的空调产品:产品族扩展难,需要抽象类都修改 ——>开闭原则倾斜*/
int main()
{
SmartHomeInterface *smartHome = new AUXSmartHome;
smartHome->CreateFridge()->Install();
smartHome->CreateTelevision()->Install();
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)