后浪 来学习吧!设计模式【10】装饰模式

设计模式【10】装饰模式

定义

动态地给一个对象添加一些额外的职责。就扩展功能而言, 它比生成子类方式更为灵活。

主要解决什么

一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

结构

  1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
  2. 具体构件(Concrete Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
  3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

装饰模式的结构图

实现

package decorator;

publicclassDecoratorPattern

{

publicstaticvoidmain(String[] args)

{

Component p=new ConcreteComponent();

p.operation();

System.out.println("---------------------------------");

Component d=new ConcreteDecorator(p);

d.operation();

}

}

//抽象构件角色

interfaceComponent

{

publicvoidoperation();

}

//具体构件角色

classConcreteComponentimplementsComponent

{

publicConcreteComponent()

{

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

}

publicvoidoperation()

{

System.out.println("调用具体构件角色的方法operation()");

}

}

//抽象装饰角色

classDecoratorimplementsComponent

{

private Component component;

publicDecorator(Component component)

{

this.component=component;

}

publicvoidoperation()

{

component.operation();

}

}

//具体装饰角色

classConcreteDecoratorextendsDecorator

{

publicConcreteDecorator(Component component)

{

super(component);

}

publicvoidoperation()

{

super.operation();

addedFunction();

}

publicvoidaddedFunction()

{

System.out.println("为具体构件角色增加额外的功能addedFunction()");

}

}

程序运行结果如下:

创建具体构件角色

调用具体构件角色的方法operation()

---------------------------------

调用具体构件角色的方法operation()

为具体构件角色增加额外的功能addedFunction()

Android中的应用

Activity继承自ContextThemeWrapper,ContextThemeWrapper继承自ContextWrapper,ContextWrapper才是继承自Context。ContextWrapper就是我们找的装饰者。

总结

**优点:**装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

**缺点:**多层装饰比较复杂。

使用场景:

1、扩展一个类的功能。

2、动态增加功能,动态撤销。

**注意事项:**可代替继承。

参考资料

JAVA设计模式总结之23种设计模式

装饰器模式

装饰模式(装饰设计模式)详解

感谢您阅读本文,希望能在微信公众号(见下方二维码)、掘金、简书、CSDN一起交流。

CoderWonder
CoderWonder_GZH.jpg

以上是 后浪 来学习吧!设计模式【10】装饰模式 的全部内容, 来源链接: utcz.com/a/31209.html

回到顶部