//组件接口
public interface Component {
public String getName();
}
---------------------------
//具体组件实现类A
public class ComponentImplA implements Component{
private String name;
public ComponentImplA(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
---------------------------
//具体组件实现类A
public class ComponentImplB implements Component {
private String name;
public ComponentImplB(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
---------------------------
public class DecoratoeTest {
public static void main(String[] args) {
Component componentImplA = new ComponentImplA("componentA");
DecoratorImplA decoratorImplA = new DecoratorImplA(componentImplA);
decoratorImplA.appendName("|append1");
System.out.println(new DecoratorImplB(componentImplA).getName());
}
}
---------------------------
//装饰器实现组件接口
public class Decorator implements Component{
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public String getName() {
return component.getName();
}
}
---------------------------
//具体的装饰器A,这里新增一个方法appendName;
public class DecoratorImplA extends Decorator {
DecoratorImplA(Component component) {
super(component);
}
//增加额外的操作
public void appendName(String name){
System.out.println(this.component.getName() + name);
}
}
---------------------------
//具体的装饰器B,这里重写原来的getName方法;
public class DecoratorImplB extends Decorator{
public DecoratorImplB(Component component) {
super(component);
}
@Override
public String getName(){
return super.getName() + "|append2";
}
}
---------------------------
返回结果
componentA|append1
componentA|append2
装饰器设计模式
于 2022-03-01 21:22:23 首次发布