人在江湖

            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與模式》中橋梁模式的例子--飛機(jī)和飛機(jī)制造商是不是也是這種靈活變換的組合?

          posted on 2011-02-08 17:19 人在江湖 閱讀(880) 評論(0)  編輯  收藏 所屬分類: design pattern
          主站蜘蛛池模板: 富源县| 娱乐| 新竹市| 金平| 汝南县| 精河县| 兰考县| 临桂县| 广安市| 眉山市| 永德县| 武隆县| 惠州市| 铜陵市| 通化市| 米脂县| 南溪县| 高阳县| 勐海县| 彰武县| 富民县| 霸州市| 弥勒县| 新河县| 灵川县| 霍城县| 包头市| 新化县| 玛纳斯县| 金山区| 灯塔市| 朝阳市| 界首市| 清水县| 娱乐| 玉树县| 屏东县| 长顺县| 东方市| 台前县| 偃师市|