装饰模式实现了可以动态地为原对象扩展方法
装饰对象与被装饰的都实现了同一个接口(或抽象类)
举个例子: 工作 可以边吃东西边工作,也可以边喝东西边工作,还可以工作的时候边吃边喝
创建共同接口 WorkComponent
package com.zhanghaobo.patterns; public interface WorkComponent {
public void work();
}
具体工作(被装饰的对象)
public class ConcreteWork implements WorkComponent { @Override
public void work() {
System.out.println("我正在工作"); } }
装饰类
public class DecoratorWork implements WorkComponent {
private WorkComponent work;
public DecoratorWork(WorkComponent work){
this.work=work;
}
@Override
public void work() {
work.work();
} }
装饰1(喝茶)
public class DrinkDecorator extends DecoratorWork { public DrinkDecorator(WorkComponent work) {
super(work);
}
@Override
public void work() {
super.work();
drinkTea();
}
public void drinkTea(){
System.out.println("顺便喝茶");
} }
装饰2(吃东西)
public class EatDecorator extends DecoratorWork { public EatDecorator(WorkComponent work) {
super(work);
} @Override
public void work() {
super.work();
eatSomething();
} public void eatSomething(){
System.out.println("顺便吃东西");
}
}
TEST:
public class Client {
public static void main(String[] args) {
//边喝茶边工作
WorkComponent wc=new DrinkDecorator(new ConcreteWork());
wc.work();
System.out.println("================================");
//边吃东西边工作
WorkComponent wc1=new EatDecorator(new ConcreteWork());
wc1.work();
System.out.println("================================");
//边吃边喝地工作
WorkComponent wc2=new DrinkDecorator(new EatDecorator(new ConcreteWork()));
wc2.work();
System.out.println("================================");
//边喝边吃地工作
WorkComponent wc3=new EatDecorator(new DrinkDecorator(new ConcreteWork()));
wc3.work();
}
}
输出结果:
我正在工作
顺便喝茶
================================
我正在工作
顺便吃东西
================================
我正在工作
顺便吃东西
顺便喝茶
================================
我正在工作
顺便喝茶
顺便吃东西