设计模式Before-after之桥接模式

before.cxx

#include <iostream>

class BlackCircle {
public:
	void what(void) {
		std::cout << "a black circle." << std::endl;
	}
};

class BlackSquare {
public:
	void what(void) {
		std::cout << "a black square." << std::endl;
	}
};

class WhiteCircle {
public:
	void what(void) {
		std::cout << "a white circle." << std::endl;
	}
};

class WhiteSquare {
public:
	void what(void) {
		std::cout << "a white square." << std::endl;
	}
};

int main(void) {
	BlackCircle blackCircle;
	blackCircle.what();

	// BlackSquare blackSquare;
	// blackSquare.what();

	// WhiteCircle whiteCircle;
	// whiteCircle.what();

	// WhiteSquare whiteSquare;
	// whiteSquare.what();
	return 0;
}

after.cxx

#include <iostream>
#include "config.hxx"

class Color {
public:
	virtual const char *getName(void) = 0;
};

class Black: public Color {
public:
	const char *getName(void) {
		return "black";
	}
};

class White: public Color {
public:
	const char *getName(void) {
		return "white";
	}
};

class Shape {
public:
	virtual void what(void) = 0;
};

class Circle: public Shape {
public:
	Circle(Color &color): color(color) {}
	void what(void) {
		std::cout << "a " << color.getName() << " circle" << std::endl;
	}
public:
	Color &color;
};

class Square: public Shape {
public:
	Square(Color &color): color(color) {}
	void what(void) {
		std::cout << "a " << color.getName() << " square" << std::endl;
	}
public:
	Color &color;
};

int main(void) {
	Shape &shape = _SHAPE_(_COLOR_());
	shape.what();
	return 0;
}

config.hxx

#define _COLOR_ Black

// #define _COLOR_ White

#define _SHAPE_ Circle

// #define _SHAPE_ Square


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值