05 Decorator装饰器模式

给一个类增加一些装饰。比如下面的例子,获取消息的时候,可以随意增加一些装饰,比如:去空格,改成大写等。可以增加一个装饰,也可以增加多个装饰,也可以任意排序嵌套装饰。

代码
package org.garen.decorator;

/**
 * 消息接口
 */
interface IMessage {
    String getMsg();
}

/**
 * 基础类
 */
class Message implements IMessage{
    private String msg;

    public Message(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}

/**
 * 抽象装饰类
 */
abstract class Decorator implements IMessage {
    IMessage message;

    public Decorator(IMessage message) {
        this.message = message;
    }

}

/**
 * 具体装饰类 - 去空格
 */
class TrimDecorator extends Decorator {

    public TrimDecorator(IMessage message) {
        super(message);
    }

    @Override
    public String getMsg() {
        return message.getMsg().trim();
    }
}

/**
 * 具体装饰类 - 大写
 */
class ToUpperDecorator extends Decorator {

    public ToUpperDecorator(IMessage message) {
        super(message);
    }

    @Override
    public String getMsg() {
        return message.getMsg().toUpperCase();
    }
}

/**
 * 测试类
 */
public class Main {
    public static void main(String[] args) {
        // 装饰1:大写、去空格
        IMessage message = new ToUpperDecorator(new TrimDecorator(new Message("   hello world!   ")));
        System.out.println(message.getMsg());

        // 装饰2:去空格
        IMessage message2 = new TrimDecorator(new Message("   hello world!   "));
        System.out.println(message2.getMsg());
    }
}

运行结果

HELLO WORLD!
hello world!

执行顺序

装饰1:
message.getMsg():

ToUpperDecorator.getMsg --> TrimDecorator.getMsg --> Message.getMsg

ToUpperDecorator.getMsg <-- TrimDecorator.getMsg <-- Message.getMsg
(“HELLO WORLD!”) <-- (“hello world!”) <-- (" hello world! ")

装饰2:
message2.getMsg():

TrimDecorator.getMsg --> Message.getMsg

TrimDecorator.getMsg <-- Message.getMsg
(“hello world!”) <-- (" hello world! ")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值