JAVA设计模式(二)装饰者模式

装饰者模式动态地将责任附加到对象上。如要扩展功能,装饰者提供了比继承更有弹性的替代方案。

装饰者可以在所委托被装饰者的行为之前与/或之后,加上自己的行为,以达到特定的目的。

类图:



package com.zaxk.study.pattern;

/**
 * 装饰者模式
 * Created by ZhuXu on 2017/11/9 0009.
 */
public class DecoratorTest {

    public static void main(String[] args) {
        Food food = new PorkRib();
        food = new Vinegar(food);
        food = new Suger(food);
        System.out.println(food.getDesc());

        System.out.println(new Sauerkraut(new Fish()).getDesc());
    }
}

abstract class Food {
    String desc;

    String getDesc() {
        return desc;
    }
}

abstract class Condiment extends Food {
    abstract String getDesc();
}

class Fish extends Food {
    Fish() {
        desc = "鱼";
    }
}

class PorkRib extends Food {
    PorkRib() {
        desc = "排骨";
    }
}

class Suger extends Condiment {

    Food food;

    Suger(Food food) {
        this.food = food;
    }

    @Override
    String getDesc() {
        return "糖" + food.getDesc();
    }
}

class Vinegar extends Condiment {

    Food food;

    Vinegar(Food food) {
        this.food = food;
    }

    @Override
    String getDesc() {
        return "醋" + food.getDesc();
    }
}

class Sauerkraut extends Condiment {

    Food food;

    Sauerkraut(Food food) {
        this.food = food;
    }

    @Override
    String getDesc() {
        return "酸菜" + food.getDesc();
    }
}


JDK中已实现的装饰者模式:输入输出流。
new BufferedReader(new InputStreamReader(new FileInputStream(file)))

猜你喜欢

转载自zhu1xu2.iteye.com/blog/2331408