装饰器设计模式

//组件接口
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值