Java-----装饰模式

[align=left][size=large][color=darkred][b]此文章问转载[/b][/color][/size][/align]
decorator 模式的功能是:给一个对象添加一些额外的职责(操作),虽然此功能可以用继承实现,但装饰模式比生成子类更灵活些。

装饰的意思:就是包装一下。把另的对象包装一下。我这里只简单示例下怎么使用。
[img]http://chenlb.com/blog/wp-content/uploads/2009/01/decorator.png[/img]
业务接口 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();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值