设计模式(5) - Bridge桥接模式

目录

1.意图

2.UML类图

3.GOF角色说明

4.代码实现


1.意图

  将一个抽象类从它的具体实现中解耦出来,这样这两个类可以独立的变化,互不影响。

2.UML类图

3.GOF角色说明

Abstraction(抽象类)
定义抽象类的接口。维护一个指向Implementor类型对象的指针。
RefinedAbstraction
扩充由Abstraction定义的接口。
Implementor
定义实现类的接口。该接口不一定要与Abstraction的接口完全一致:事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些操作的较高层次的操作。
ConcreteImplementor
实现Implementor接口并定义它的具体实现。

4.代码实现

#include<iostream>
using namespace std;

//Implementor
class DrawImplementor {
public:
	virtual void drawSquare(double) = 0;
	virtual ~DrawImplementor() {
	}
};

// ConcreteImplementor A
class DrawWithBrush: public DrawImplementor {
public:
	DrawWithBrush() {
	}
	virtual ~DrawWithBrush() {
	}

	void drawSquare(double side) {
		cout<<"DrawWithBrush->square with side="<<side<<endl;
	}
};

// ConcreteImplementor B
class DrawWithPencil: public DrawImplementor {
public:
	DrawWithPencil() {
	}
	virtual ~DrawWithPencil() {
	}

	void drawSquare(double side) {
		cout<<"DrawWithPencil->square with side="<<side<<endl;
	}
};

// Abstraction
class Shape {
public:
	virtual void draw() = 0;
	virtual void resize(double) = 0;
	virtual ~Shape() {
	}
};

// Refined Abstraction
class Square: public Shape {
public:
	Square(double s, DrawImplementor& impl):
		side(s),implementor(impl) {
	}
	virtual ~Square() {
	}

	void draw() {
		implementor.drawSquare(side);
	}

	void resize(double pct) {
		side *= pct;
	}
private:
	double side;
	DrawImplementor& implementor;
};

int main(int argc, char *argv[]) {
	DrawWithBrush brush;
	DrawWithPencil pencil;

	Square sq1(1,brush);
	Square sq2(2,pencil);

	sq1.resize(10);
	sq1.draw();
	sq2.resize(10);
	sq2.draw();

	return 0;

}

  运行结果:
  DrawWithBrush->square with side=10
  DrawWithPencil->square with side=20

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值