c++设计模式系列_C++进阶系列之设计模式(4)建造者模式和抽象工厂模式

1、建造者模式 一个对象的构建比较复杂,将一个对象的构建和对象的表示进行分离!!! 2、具体实现 (1)、代码如下
#include
#include
using namespace std;

class House{
public:
void setDoor(string door){
this->m_door = door;
}
void setWall(string wall){
this->m_wall = wall;
}
void setWindow(string window){
this->m_window = window;
}
public:
string getDoor(){
return m_door;
}
string getWall(){
return m_wall;
}
string getWindow(){
return m_window;
}
private:
string m_door;
string m_wall;
string m_window;
};

//请工程队来建造房子
class Build{
public:
House *setHouse(){

}
private:
};
int main(void){
//这样写不好,是客户直接造房子;
House *house = new House;
house->setDoor("门");
house->setWall("墙面");
house->setWindow("窗口");

delete house;

return 0;
}
3、抽象工厂 只能生产一个产品; 4、具体实现 (1)、代码如下
#include
using namespace std;

class Fruit;
class AbstractFactory{
public:
virtual Fruit *CreateBanana() = 0;
virtual Fruit *CreateApple() = 0;
private:
};

class Fruit{
public:
virtual void sayname() = 0;
private:
};

class NorthBanana : public Fruit{
public:
virtual void sayname(){
cout<<"我是北方香蕉"<<endl;
}
};
class NorthApple : public Fruit{
public:
virtual void sayname(){
cout<<"我是北方苹果"<<endl;
}
};

class SouthBanana : public Fruit{
public:
virtual void sayname(){
cout<<"我是南方香蕉"<<endl;
}
};

class SouthApple : public Fruit{
public:
virtual void sayname(){
cout<<"我是南方苹果"<<endl;
}
};

class NorthFactory : public AbstractFactory{
public:
virtual Fruit *CreateBanana(){
return new NorthBanana;
}
virtual Fruit *CreateApple(){
return new NorthApple;
}
private:
};

class SouthFactory : public AbstractFactory{
public:
virtual Fruit *CreateBanana(){
return new SouthBanana;
}
virtual Fruit *CreateApple(){
return new SouthApple;
}
private:
};
int main(void){
Fruit *fruit = NULL;
AbstractFactory *af = NULL;
//---------------------------
af = new SouthFactory;
fruit = af->CreateApple();
fruit->sayname();
fruit = af->CreateBanana();
fruit->sayname();
//---------------------------
af = new NorthFactory;
fruit = af->CreateApple();
fruit->sayname();
fruit = af->CreateBanana();
fruit->sayname();

delete af;

return 0;
}
(2)、运行结果

83a5e7493862ce955803e750f6dc72cd.png

(3)、抽象模式 缺点:抽象工厂的产品线都被写死了;只能生产这2种产品; 推荐阅读: Linux/C/C++/嵌入式交流群建立,欢迎加入学习! C++进阶系列之设计模式(1)---设计模式的核心思想 C++进阶系列之设计模式(2)---单例模式 C++进阶系列之设计模式(3)---工厂模式和原型模式

加我微信,备注【C++】

拉你到 Linux/C/C++/嵌入式方向交流群学习

31aeb9d01b9a53b8a163f8acf9249de2.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值