赞
踩
本文章属于专栏《设计模式(极简c++版)》
继续上一篇《原型模式(极简c++)》。本章简要说明桥接模式。本文分为模式说明、本质思想、实践建议、代码示例四个部分。
- #include <iostream>
-
- // 实现部分接口:颜色
- class Color {
- public:
- virtual void applyColor() const = 0;
- };
-
- // 具体实现类:红色
- class RedColor : public Color {
- public:
- void applyColor() const override {
- std::cout << "Red" << std::endl;
- }
- };
-
- // 具体实现类:绿色
- class GreenColor : public Color {
- public:
- void applyColor() const override {
- std::cout << "Green" << std::endl;
- }
- };
-
- // 抽象部分类:形状
- class Shape {
- protected:
- Color* color;
-
- public:
- Shape(Color* c) : color(c) {}
-
- virtual void draw() const = 0;
- };
-
- // 扩展的抽象部分类:圆形
- class Circle : public Shape {
- public:
- Circle(Color* c) : Shape(c) {}
-
- void draw() const override {
- std::cout << "Drawing Circle with color ";
- color->applyColor();
- }
- };
-
- // 扩展的抽象部分类:矩形
- class Rectangle : public Shape {
- public:
- Rectangle(Color* c) : Shape(c) {}
-
- void draw() const override {
- std::cout << "Drawing Rectangle with color ";
- color->applyColor();
- }
- };
-
- int main() {
- Color* red = new RedColor();
- Color* green = new GreenColor();
-
- Shape* redCircle = new Circle(red);
- Shape* greenRectangle = new Rectangle(green);
-
- redCircle->draw(); // 输出: Drawing Circle with color Red
- greenRectangle->draw(); // 输出: Drawing Rectangle with color Green
-
- delete red;
- delete green;
- delete redCircle;
- delete greenRectangle;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。