装饰模式
来源:互联网 发布:mariadb与mysql 编辑:程序博客网 时间:2024/06/10 09:15
decorator 模式的功能是:给一个对象添加一些额外的职责(操作),虽然此功能可以用继承实现,但装饰模式比生成子类更灵活些。
装饰的意思:就是包装一下。把另的对象包装一下。我这里只简单示例下怎么使用。
业务接口 Component:
package com.chenlb.dp.decorator;
/**
* 业务接口
*/
public interface Component {
void operation();
}
具体业务 ConcreteComponent:
package com.chenlb.dp.decorator;
/**
* 具体业务类.
*/
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("I'm "+this.getClass().getName());
}
}
装饰 Decorator:
package com.chenlb.dp.decorator;
/**
* 装饰类.
*/
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
执行前装饰 BeforeDecorator:
package com.chenlb.dp.decorator;
/**
* 在业务执行前加点额外的操作.
*/
public class BeforeDecorator extends Decorator {
public BeforeDecorator(Component component) {
super(component);
}
public void operation() {
before();
super.operation();
}
private void before() {
System.out.println("before: I'm "+this.getClass().getName());
}
}
执行后装饰 AfterDecorator:
package com.chenlb.dp.decorator;
/**
* 在业务执行完后添加额外的操作.
*/
public class AfterDecorator extends Decorator {
public AfterDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
after();
}
private void after() {
System.out.println("after: I'm "+this.getClass().getName());
}
}
运行示例 Demo:
package com.chenlb.dp.decorator;
public class Demo {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.operation();
System.out.println("----------------------------------------");
component = new BeforeDecorator(new ConcreteComponent());
component.operation();
System.out.println("----------------------------------------");
component = new AfterDecorator(new ConcreteComponent());
component.operation();
System.out.println("----------------------------------------");
component = new AfterDecorator(new BeforeDecorator(new ConcreteComponent()));
component.operation();
System.out.println("----------------------------------------");
component = new BeforeDecorator(new AfterDecorator(new ConcreteComponent()));
component.operation();
}
}
- 装饰模式-撤销装饰
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- 装饰模式
- ExtJs下拉联动控制选择
- 搬到javaeye去了
- 23种设计模式的趣说详解
- Gray-level Co-occurrence Matrix 灰度共生矩阵
- IPsec VPN 基本配置说明
- 装饰模式
- (字母、数字、Email、网址、电话号码、汉字、身份证号码)正则表达式验证代码
- c#内存回收
- Android + eclipse +ADT安装完全教程
- 2.2Subset Sums
- android耳机插入检测
- vc操作word读写
- ExtJS学习笔记
- 关于无法把程序添加到打开方式的解决办法