人在江湖

            BlogJava :: 首頁 :: 聯(lián)系 :: 聚合  :: 管理
            82 Posts :: 10 Stories :: 169 Comments :: 0 Trackbacks

          /** "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" */

          interface Shape {

             public void draw();                                            // low-level

             public void resizeByPercentage(double pct);     // high-level

          }

          /** "Refined Abstraction" */

          class CircleShape implements Shape {

             private double x, y, radius;

             private DrawingAPI drawingAPI;

             public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {

                 this.x = x;  this.y = y;  this.radius = radius; 

                 this.drawingAPI = drawingAPI;

             }

             // low-level i.e. Implementation specific

             public void draw() {

                  drawingAPI.drawCircle(x, y, radius);

             }   

             // high-level i.e. Abstraction specific

             public void resizeByPercentage(double pct) {

                  radius *= pct;

             }

          }

          /** "Client" */

          class BridgePattern {

             public static void main(String[] args) {

                 Shape[] shapes = new Shape[2];

                 shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());

                 shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());

                 for (Shape shape : shapes) {

                     shape.resizeByPercentage(2.5);

                     shape.draw();

                 }

             }

          }

           

          Bridge遵循的是接口隔離原則的典型。比如,隨著時代的發(fā)展,槍在不停的變化改進(jìn)。與此同時槍的子彈也在改進(jìn),很多子彈賦予了新功能:比如信號彈,救援彈,甚至是炸彈。這樣,槍是抽象的同時,子彈也是抽象的。二者組合起來變換無窮。仔細(xì)想一下《java與模式》中橋梁模式的例子--飛機和飛機制造商是不是也是這種靈活變換的組合?

          posted on 2011-02-08 17:19 人在江湖 閱讀(882) 評論(0)  編輯  收藏 所屬分類: design pattern
          主站蜘蛛池模板: 江阴市| 通州市| 霸州市| 宝丰县| 渭南市| 岱山县| 凤山县| 海原县| 岢岚县| 上杭县| 台州市| 平顶山市| 简阳市| 雷州市| 阿瓦提县| 西乌珠穆沁旗| 江阴市| 观塘区| 河间市| 玛沁县| 仙居县| 湟源县| 平原县| 通州区| 米林县| 井研县| 岳西县| 西城区| 安西县| 德江县| 曲阜市| 墨脱县| 收藏| 云梦县| 陆良县| 陕西省| 北辰区| 丰台区| 新宾| 唐海县| 三江|