关于桥接模式的几处疑惑

12-03-08 bugstorms
最近在学习设计模式,在“设计模式”的板块中看到“桥接模式”时疑惑重重,不说不快,欢迎拍砖:

引用页“http://www.jdon.com/designpatterns/bridge.htm”

疑惑1、对Coffee的抽象不够彻底,没有将行为(是否加奶精)与实例的类型(杯型)进行清晰区分,

public abstract class Coffee

{

   CoffeeImp coffeeImp;

   public void setCoffeeImp() {

     this.CoffeeImp = CoffeeImpSingleton.getTheCoffeImp();//觉得此处实现不够优雅,用单态创建行为有何特殊用意?

   }

  public CoffeeImp getCoffeeImp() {return this.CoffeeImp;}

   public abstract void pourCoffee();

}

疑惑2、

CoffeeImpSingleton此类不构造的话不能work,不像是下帖讲的单态的行为,

http://www.jdon.com/designpatterns/singleton.htm

代码改了一下,可以直接work:

public class Launching {

    public static void main(String[] args) {
        Launching launching = new Launching();
        launching.printServiceLog();
    }

    private void printServiceLog() {
        new Medium(new MilkCoffee()).pourCoffee();//中杯加奶
        new Medium(new FragrantCoffee()).pourCoffee();//中杯原味
        new SuperSize(new MilkCoffee()).pourCoffee();//大杯加奶
        new SuperSize(new FragrantCoffee()).pourCoffee();//大杯原味
    }

    interface CoffeeBehavior {//行为更适合定义成接口
        void setFavor();
    }


    abstract class Coffee {
        protected CoffeeBehavior coffeeBehavior;

        protected void setCoffeeBehavior(CoffeeBehavior coffeeBehavior) {
            this.coffeeBehavior = coffeeBehavior;
        }

        protected abstract void pourCoffee();
    }

    //中杯
    class Medium extends Coffee {
        public Medium(CoffeeBehavior coffeeBehavior) {
            super.setCoffeeBehavior(coffeeBehavior);
        }

        @[author]Override[/author]
        public void pourCoffee() {
            System.out.print("中杯:");
            coffeeBehavior.setFavor();
        }
    }

    //大杯
    class SuperSize extends Coffee {
        public SuperSize(CoffeeBehavior coffeeBehavior) {
            super.setCoffeeBehavior(coffeeBehavior);
        }

        @[author]Override[/author]
        public void pourCoffee() {
            System.out.print("大杯:");
            coffeeBehavior.setFavor();
        }
    }

    //加奶
    class MilkCoffee implements CoffeeBehavior {
        public void setFavor() {
            System.out.println("加了美味的牛奶");
        }
    }

    //不加奶
    class FragrantCoffee implements CoffeeBehavior {
        public void setFavor() {
            System.out.println("什么也没加,清香");
        }
    }
}
<p>

[该贴被bugstorms于2012-03-08 17:27修改过]

    

banq
2012-03-08 18:14
不错,改得比较优雅。

桥模式使用动态代理Mixin后,会更加优雅,实际类似一种DCI架构。

猜你喜欢