设计模式--------装饰器

说明:动态的给对象添加一些额外的功能
角色:component(构件) ConcreteComponent(具体构件) Decorator(装饰器) ConcreteDecorator(具体装饰器)
Component
定义一个对象接口,可以给这些对象动态地添加职责。
ConcreteComponent
是定义了一个具体的对象,也可以给这个对象添加一些职责。
Decorator
装饰抽象类,继承了Component,扩展了Component类的功能,对于Component无需知道Decorator。
ConcreteDecorator
具体实现的装饰对象,给Component添加职责的功能。
比如我们有一个机器人,最初的功能只是对话和唱歌,现在我们要添加额外的功能让他能跳舞拖地
首先定义一个机器人接口里面有个dosometing方法,
然后实现这个方法对话唱歌,
再用一个类实现这个方法附加新功能

//需要被装饰的对象   Component
public interface Robot {
    void doSometing();
}





//ConcreteComponent
public class OneRobot implements Robot{
    @Override
    public void doSometing() {
        System.out.println("唱歌");
        System.out.println("对话");
    }
}


//装饰器
public class RobotDecorator implements Robot{
    private Robot robot;

    public RobotDecorator(Robot robot) {
        this.robot = robot;
    }

    @Override
    public void doSometing() {
        robot.doSometing();
    }
    public void doOther(){
        System.out.println("拖地");
        System.out.println("跳舞");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值