装饰者模式

旧时模样 提交于 2020-02-05 04:17:06

装饰者模式

     对原有功能进行增强。装饰模式含有一下几部分。抽象构件、具体构件、抽象装饰、具体装饰。原本功能是具体构件中的功能,现在要通过装饰来对具体构建进行增强。

1. 抽象构件

    定义一个接口,来确定他的子类要实现怎样的功能。

package com.wx.demo01;

//抽象构建角色
public interface Component {
    public void operation();
}

2. 具体构件

   定义具体构件类,实现抽象构件接口,此类就是原本的功能。

package com.wx.demo01;


//具体构建角色
public class ConcreteComponent implements Component{
    public void operation() {
        System.out.println("调用具体构件角色的方法operation()");
    }
    public ConcreteComponent(){

        System.out.println("创建具体构建角色");
    }
}

3.抽象装饰

   现在需要对原本功能进行装饰增强。定义抽象装饰类,实现抽象构件接口。

package com.wx.demo01;

//抽象装饰角色
public class Decorator implements Component{

    private Component component;
    public  Decorator(Component component){
        this.component = component;
    }
    public void operation() {
        component.operation();
    }
}

4.具体装饰

   继承抽象装饰,在具体装饰中添加增加的功能。

package com.wx.demo01;

//具体装饰角色
public class ConcreteDecorator extends Decorator{
    public ConcreteDecorator(Component component) {
        super(component);
    }

    public void operation(){
        super.operation();
        addedFunction();
    }
    public void addedFunction(){
        System.out.println("为具体构件角色增加额外的功能addedFunction()");
    }
}

5. 测试类

package com.wx.demo01;

public class DecoratorPattern {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component.operation();
        System.out.println("-----------------------");
        Component d = new ConcreteDecorator(component);
        d.operation();
    }
}

6. 测试结果

                                  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!