1、定义及作用
该模式以对客户端透明的方式扩展对象的功能。
2、涉及角色
抽象构件角色:定义一个抽象接口,来规范准备附加功能的类。
具体构件角色:将要被附加功能的类,实现抽象构件角色接口。
抽象装饰者角色:持有对具体构件角色的引用并定义与抽象构件角色一致的接口。
具体装饰角色:实现抽象装饰者角色,负责为具体构件添加额外功能。
3、简单实现
抽象构件角色java 代码
- package decorator;
-
-
-
-
-
- public interface InterfaceComponent {
-
-
-
-
-
- public void say();
- }
- package decorator;
-
-
-
-
-
- public class Component implements InterfaceComponent{
-
- public void say() {
-
- System.out.println("Component.say():原组件的方法!");
- }
-
- }
- package decorator;
-
-
-
-
-
- public abstract class AbstractDecorator implements InterfaceComponent{
-
- private InterfaceComponent component;
-
- public AbstractDecorator(InterfaceComponent component){
- this.component = component;
- }
-
-
-
-
- protected void preSay(){};
-
-
-
-
-
- protected void afterSay(){};
-
- public void say(){
-
- preSay();
- component.say();
- afterSay();
-
- };
- }
- package decorator;
-
-
-
-
-
- public class DecoratorTwo extends AbstractDecorator{
-
- public DecoratorTwo(InterfaceComponent component) {
- super(component);
-
- }
-
-
-
-
- protected void preSay(){
- System.out.println("DecoratorTwo.preSay():装饰者二的preSay()方法!");
- }
-
-
-
-
- protected void afterSay(){
- System.out.println("DecoratorTwo.afterSay():装饰者二的afterSay()方法!");
- }
-
- }
- package decorator;
-
-
-
-
-
- public class DecoratorOne extends AbstractDecorator{
-
- public DecoratorOne(InterfaceComponent component) {
- super(component);
-
- }
-
-
-
- protected void preSay(){
- System.out.println("DecoratorOne.preSay():装饰者一的preSay()方法!");
- }
-
-
-
-
- protected void afterSay(){
- System.out.println("DecoratorOne.afterSay():装饰者一的afterSay()方法!");
- }
-
-
-
-
- public static void main(String[] args) {
-
- InterfaceComponent interfaceComponent = new DecoratorTwo(new DecoratorOne(new Component()));
- interfaceComponent.say();
-
-
-
-
-
-
-
-
- }
- }
4、优缺点
优点:1)提供比继承更多的灵活性 2)使用不同的装饰组合可以创造出不同行为的组合 3)需要的类的数目减少
缺点:1)灵活性带来比较大的出错性 2)产生更多的对象,给查错带来困难
|