[C++]建造者模式

建造者模式,是将一个复杂的对象的构建与它的表示分离,使
得同样的构建过程可以创建不同的表示。创建者模式隐藏了复杂对象的创建过程,它把复杂对象的创建过程加以抽象,通过子类继承或者重载的方式,动态的创建具有复合属性的对象。

C++代码如下:

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式- 建造者模式

#include <iostream>

// 建造者模式:通过统一的规范的抽象类,子类集成后实现不同的功能。
//             所以子类都必须满足基类的纯虚函数方法。

using namespace std;

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p){delete(p); (p)=NULL;} }
#endif

// 抽象基类,包括多个子类必须实现的方法
class buildPerson {
public:
	virtual void createHead() = 0;
	virtual void createBody() = 0;
	virtual void createHand() = 0;
	virtual void createFoot() = 0;
};

// 具体的实现类
class buildThinPerson: public buildPerson {
public:
	void createHead() {
		cout << "thin head" << endl;
	}
	void createBody() {
		cout << "thin body" << endl;
	}
	void createHand() {
		cout << "thin hand" << endl;
	}
	void createFoot() {
		cout << "thin foot" << endl;
	}
};

class buildFatPerson : public buildPerson {
public:
	void createHead() {
		cout << "fat head" << endl;
	}
	void createBody() {
		cout << "fat body" << endl;
	}
	void createHand() {
		cout << "fat hand" << endl;
	}
	void createFoot() {
		cout << "fat foot" << endl;
	}
};

// 建造者类,负责根据不同的对象,调用不同的已规范好的实现
class buildClass {
public:
	void construct(buildPerson* buildperson) {
		buildperson_ = buildperson;
	}

	void constructPerson() {
		if (buildperson_) {
			buildperson_->createHead();
			buildperson_->createBody();
			buildperson_->createHand();
			buildperson_->createFoot();
		}
	}

private:
	buildPerson* buildperson_ = nullptr;
};

int main()
{
	// 建造者对象
	buildClass* buildclass = new buildClass();

	// 具体的person对象,传入建造者,由建造者调用已规范好的方法。
	buildThinPerson* buildthinperson = new buildThinPerson();
	buildclass->construct(buildthinperson);
	buildclass->constructPerson();

	SAFE_DELETE(buildthinperson);

	buildFatPerson* buildfatperson = new buildFatPerson();
	buildclass->construct(buildfatperson);
	buildclass->constructPerson();

	SAFE_DELETE(buildfatperson);
	SAFE_DELETE(buildclass);

	return 0;
}


github源码路径:https://github.com/dangwei-90/Design-Mode

持续更新中

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值