装饰模式

装饰模式

动态地给一个对象添加一个额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。

代码实现

Component抽象类——定义一个对象接口,可以给这些对象动态的添加一些职责。

public abstract class Component{
    public abstract void operation();
}

ConcreteComponent类——定义一个具体的对象。

public class ConcreteComponent extends Component{ 
    public void operation(){
        System.out.println("具体对象的操作!");
    }
}

Decorator类——装饰抽象类,继承了Component接口,从外部扩展Component类的功能。

public abstract class Decortor extends Component{
    protected Component component;

    public void setComponent(Component component){
        this.component = component;
    }

    //重写operation()方法,实际执行component的operation()
    public void operation(){
        if(component != null){
            component.operation();
        }
    }
}

ConcreteComponentA和ConcreteComponentB类——装饰类的具体实现

public class ConcreteComponentA{
    private String addedState;//本类独有的属性,区别于ConcreteComponentB

    public void operation(){
        super.operation();//先运行父类的operation()方法,再去执行本类特有的功能,相当于对原Component进行了装饰
        addedState = "New State";
        System.out.println("具体装饰对象A的操作");
    }
}


public class ConcreteComponentB{

    //本类独有的方法,区别于ConcreteComponentA类
    public void addedBehavior(){

    }

    public void operation(){
        super.operation();
        addedBehavior();
        System.out.println("具体装饰对象B的操作");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值