205装饰器模式

34 阅读1分钟

定义

动态地给一个对象添加一些额外的功能,就增加功能类来说,装饰模式比生成子类更为灵活。(在原先类上包裹)

类图

图片3.png

代码

public class DecoratorPattern {
    public static void main(String[] args) {
    //    new com.mxy.dp.RobotDecorator().doSomething();
        new RobotDecorator(new FirstRobot()).doSomething();
    }

}

interface Robot{
    void doSomething();
}

class FirstRobot implements  Robot{
    @Override
    public void doSomething() {
        System.out.println("对话");
        System.out.println("唱歌");
    }
}
// 装饰器--新增功能类
class RobotDecorator implements Robot{
    private Robot robot;

    public RobotDecorator() {
    }

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

    @Override
    public void doSomething() {
        robot.doSomething();
        System.out.println("新增----扫地");
    }
}