博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
装饰者模式
阅读量:2256 次
发布时间:2019-05-09

本文共 1483 字,大约阅读时间需要 4 分钟。

装饰者模式

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

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. 测试结果

                                  

转载地址:http://zsrdb.baihongyu.com/

你可能感兴趣的文章
调用dll
查看>>
Linux统计文件行数
查看>>
linux查看文件和文件夹大小
查看>>
linux下C获取文件的大小
查看>>
linux C文件到文件,文件到文件夹,文件夹到文件夹的拷贝
查看>>
linux grep命令
查看>>
Linux GCC常用命令
查看>>
linux环境变量set env export细解
查看>>
Python之os.walk和os.path.walk
查看>>
python 之 分割参数getopt
查看>>
内存映射文件原理探索
查看>>
linux shell 字符串操作
查看>>
shell 逻辑运算符、逻辑表达式
查看>>
数据挖掘学习—孤立点分析(异类分析)
查看>>
一致性hash算法 - consistent hashing
查看>>
Linux directory structure
查看>>
如何使用git回退部分修改
查看>>
pytho获取磁盘剩余空间
查看>>
linux 普通用户添加ssh或禁止ssh
查看>>
进程/线程同步——Critical Section,Mutex,Semaphore,Event区别
查看>>