设计模式(十):装饰模式Decorate(结构型模式)

本文通过具体实例介绍了装饰模式的概念及其在Java编程中的应用。装饰模式允许在不改变原有对象的情况下为其添加新的功能,使得功能扩展更加灵活。文章展示了如何通过继承和组合实现装饰者模式,并给出了运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子:

package com.zoey.designPattern.Decorator;
/*
 * 装饰模式(Decorator):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活
 * Component是定义一个对象接口,可以给这些对象动态地添加职责。
 */
public abstract class Component {
    public abstract void Operation();
}
package com.zoey.designPattern.Decorator;
//ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责
public class ConcreteComponent extends Component {

    @Override
    public void Operation() {
        System.out.println("具体对象的操作");
    }

}
package com.zoey.designPattern.Decorator;
//Decorator装饰抽象类,继承了component,从外类来扩展component类的功能,但对于Component来说,
//是无需知道Decorator的存在的
public class Decorator extends Component {
    protected Component component;


    @Override
    public void Operation() {
        if(component != null){
            component.Operation();
        }
    }

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


}
package com.zoey.designPattern.Decorator;
//ConcreteDecoratorA具体装饰对象,起到给Component添加职责的功能
public class ConcreteDecoratorA extends Decorator {
    @SuppressWarnings("unused")
    private String addedState;

    public void Operation(){
        super.Operation();
        addedState = "New State";
        System.out.println("具体装饰对象A的操作");
    }
}
package com.zoey.designPattern.Decorator;
//ConcreteDecoratorB具体装饰对象,起到给Component添加职责的功能
public class ConcreteDecoratorB extends Decorator {
   public void Operation(){
        super.Operation();
        addedbehavior();
        System.out.println("具体装饰对象B的操作");
    }

    private void addedbehavior(){
        System.out.println("一条测试的方法!");
    }
}
package com.zoey.designPattern.Decorator;

public class Test {
    /*
     * 装饰模式,优点:有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑
     */
    public static void main(String[] args) {
        ConcreteComponent c = new ConcreteComponent();
        ConcreteDecoratorA d1 = new ConcreteDecoratorA();
        ConcreteDecoratorB d2 = new ConcreteDecoratorB();

        d1.setComponent(c);
        d2.setComponent(d1);
        d2.Operation();

    }

}

结果:
具体对象的操作
具体装饰对象A的操作
一条测试的方法!
具体装饰对象B的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值