漫谈设计模式--3分钟理解桥接模式:笔和画的关系
其實不需要3分鐘,3秒鐘就夠了,記住橋接模式就是如此簡單:一句話,筆有千般形,畫有萬變化。
下面的僅僅助于理解。
1. 定義
The?bridge pattern?is a?design pattern?used in?software engineering?which is meant to?"decouple an?abstraction?from its?implementation?so that the two can vary independently"
From Wikipedia, the free encyclopedia:http://en.wikipedia.org/wiki/Bridge_pattern
2. 應用場景
? ?The bridge pattern is useful when both the class as well as what it does vary often。
? ?例如用筆作畫,筆有鉛筆、鋼筆、毛筆、水筆、電腦等;圖形有:直線、圓、三角形、樹葉等等。各自獨立變化。
3. 結構
Abstraction (abstract class)3. 實例
The following?Java?(SE 6) program illustrates the 'shape' example given below.
簡單描述就是筆和圖形的關系:
筆有鉛筆、鋼筆、毛筆、水筆等等;圖形有:直線、圓、三角形、樹葉等等。各自獨立變化。
/** "Implementor" */ interface DrawingAPI {public void drawCircle(double x, double y, double radius); }/** "ConcreteImplementor" 1/2 */ class DrawingAPI1 implements DrawingAPI {public void drawCircle(double x, double y, double radius) {System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);} }/** "ConcreteImplementor" 2/2 */ class DrawingAPI2 implements DrawingAPI {public void drawCircle(double x, double y, double radius) {System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);} }/** "Abstraction" */ abstract class Shape {protected DrawingAPI drawingAPI;protected Shape(DrawingAPI drawingAPI){this.drawingAPI = drawingAPI;}public abstract void draw(); // low-levelpublic abstract void resizeByPercentage(double pct); // high-level }/** "Refined Abstraction" */ class CircleShape extends Shape {private double x, y, radius;public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {super(drawingAPI);this.x = x; this.y = y; this.radius = radius;}// low-level i.e. Implementation specificpublic void draw() {drawingAPI.drawCircle(x, y, radius);}// high-level i.e. Abstraction specificpublic void resizeByPercentage(double pct) {radius *= pct;} }/** "Client" */ class BridgePattern {public static void main(String[] args) {Shape[] shapes = new Shape[] {new CircleShape(1, 2, 3, new DrawingAPI1()),new CircleShape(5, 7, 11, new DrawingAPI2()),};for (Shape shape : shapes) {shape.resizeByPercentage(2.5);shape.draw();}} }It will output:
API1.circle at 1.000000:2.000000 radius 7.5000000 API2.circle at 5.000000:7.000000 radius 27.500000?無聊加入下面的文字,湊夠博客園的文字篇幅要求,不用看。
Bridge模式的概念
Bridge 模式是構造型的設計模式之一。Bridge模式基于類的最小設計原則,通過使用封裝,聚合以及繼承等行為來讓不同的類承擔不同的責任。它的主要特點是把抽象(abstraction)與行為實現(implementation)分離開來,從而可以保持各部分的獨立性以及應對它們的功能擴展。
Bridge模式的應用場景
面向對象的程序設計(OOP)里有類繼承(子類繼承父類)的概念,如果一個類或接口有多個具體實現子類,如果這些子類具有以下特性:
- 存在相對并列的子類屬性。
- 存在概念上的交叉。
- 可變性。
我們就可以用Bridge模式來對其進行抽象與具體,對相關類進行重構。
轉載于:https://www.cnblogs.com/davidwang456/p/4025926.html
總結
以上是生活随笔為你收集整理的漫谈设计模式--3分钟理解桥接模式:笔和画的关系的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 改变eclipse工程中代码的层次结构
- 下一篇: 八种架构设计模式及其优缺点概述