设计模式之装饰者模式

本文介绍装饰者模式的概念及其在面向对象设计中的应用。通过具体的Java代码示例,展示了如何利用装饰者模式为对象动态添加职责,同时提供了一种比继承更灵活的扩展方式。文章深入探讨了装饰者模式的实现细节。

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

什么是装饰者模式

装饰者模式动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。这就是面向对象设计中常提到的优先使用组合而不是继承。

UML图

装饰者模式

图中抽象类Component是被装饰者基类,ConcreteComponent是将要动态地加上新行为的对象,它扩展了Component。Decorator是装饰者共同实现的接口或者是抽象类。ConcreteDecoratorA和ConcreteDecoratorB都是实现或扩展了Decorator的装饰者,它们都有一个Component的私有实例变量,实现了抽象类的方法,并且可以加上新的方法从而实现扩展功能。

代码实现

Component

/**
 * Created by yrs on 2017/7/2.
 */
public abstract class Component {
    public abstract void say();
}

ConcreteComponent

/**
 * Created by yrs on 2017/7/2.
 */
public class ConcreteComponent extends Component {
    @Override
    public void say() {
        System.out.println("this is ConcreteComponent.");
    }
}

Decorator

/**
 * Created by yrs on 2017/7/2.
 */
public abstract class Decorator extends Component {

}

ConcreteDecoratorA

/**
 * Created by yrs on 2017/7/2.
 */
public class ConcreteDecoratorA extends Decorator {

    private Component component;

    public ConcreteDecoratorA(Component component) {
        this.component = component;
    }

    @Override
    public void say() {
        preSay();
        component.say();
        sufSay();
    }

    public void preSay() {
        System.out.println("Welcome everyone!");
    }

    public void sufSay() {
        System.out.println("Thank you!");
    }
}

ConcreteDecoratorB

/**
 * Created by yrs on 2017/7/2.
 */
public class ConcreteDecoratorB extends Decorator {

    private Component component;

    public ConcreteDecoratorB(Component component) {
        this.component = component;
    }

    @Override
    public void say() {
        component.say();
        sayHelp();
    }

    public void sayHelp() {
        System.out.println("please help me!");
    }

}

Test

/**
 * Created by yrs on 2017/7/2.
 */
public class Test {
    public static void main(String [] args) {

        //用ConcreteDecoratorA类装饰ConcreteComponent对象
        component = new ConcreteDecoratorA(component); 

        //用ConcreteDecoratorB类装饰ConcreteComponent对象
        component = new ConcreteDecoratorB(component);

        component.say();
    }
}

装饰者模式的重点是装饰者有一个被装饰者的实例变量

Java IO中的装饰者模式

Java IO中的装饰者模式

代码下载:https://github.com/ByrsH/Design-Patterns/tree/master/Design%20Patterns/src/main/java/com/yrs/decorator

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值