装饰模式是在不改变原来具体实现接口类的前提下,增加了一些实现。
package com.wq.decorator;
/**
* 抽象构建角色的具体实现
*/
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("功能1");
}
}
package com.wq.decorator;
/**
* 抽象构建角色
*/
public interface Component {
void doSomething();
}
装饰类
package com.wq.decorator;
/**
* 装饰角色要持有一个Component的具体实现
*/
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void doSomething() {
component.doSomething();
}
}
继承装饰类的具体实现类
package com.wq.decorator;
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
this.doAnotherThing();
}
public void doAnotherThing(){
System.out.println("装饰功能");
}
public static void main(String[] args) {
ConcreteDecorator1 concreteDecorator1 = new ConcreteDecorator1(new Decorator(new ConcreteComponent()));
concreteDecorator1.doSomething();
}
}
运行结果:
16:44:56: Executing task 'ConcreteDecorator1.main()'...
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes
> Task :ConcreteDecorator1.main()
功能1
装饰功能
BUILD SUCCESSFUL in 4s
2 actionable tasks: 2 executed
16:45:00: Task execution finished 'ConcreteDecorator1.main()'.