装饰模式(Decorator pattern)

时间:2023-02-10 07:06:59

装饰模式(Decorator pattern): 又名包装模式(Wrapper pattern), 它以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任。换言之,客户端并不会觉得对象在装饰前和装饰后有什么不同。

装饰模式可以在不创造更多子类的情况下,将对象的功能加以扩展。

装饰模式 把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展完全是透明的。

组成

  1.抽象构件角色(Component):给出一个抽象类或接口,以规范准备接收附加责任的对象。

  2.具体构件角色(Concrete Component):定义一个将要接收附加责任的类。

  3.装饰角色(Decorator):持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口

  4.具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。

特点

  1. 装饰对象和真实对象有相同的接口。这样客户端对象就可以以和真实对象相同的方式和装饰对象交互。
  2. 装饰对象包含一个真实对象的引用(reference)。
  3. 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展(感觉跟代理模式有点像,都是持有真实对象的引用,转发请求前后增加附加功能)。

代码实例:

抽象的构建角色:

 public interface Componment  //抽象的构件角色,给出一个抽象接口,规范准备接收附加责任的对象
{
public void doSomething();
}

具体的构建角色:

 public class ConcreteComponment implements Componment//具体构建角色,定义一个要接收附加责任的类
{
public void doSomething()
{
System.out.println("功能A"); }
}

装饰角色:

 public class Decorator implements Componment //装饰角色,
{
private Componment componment; //持有一个构件(Componment)对象的引用 public Decorator(Componment componment)
{
this.componment = componment;
}
public void doSomething()
{
componment.doSomething();
}
}

具体装饰角色1:

 public class ConcreteDecorator1 extends Decorator //具体装饰角色1
{ public ConcreteDecorator1(Componment componment)
{
super(componment);
} public void doSomething()
{
super.doSomething();
this.doAnotherthing();
} private void doAnotherthing()
{
System.out.println("功能B");
} }

具体装饰角色2:

 public class ConcreteDecorator2 extends Decorator
{
public ConcreteDecorator2(Componment componment)
{
super(componment);
} @Override
public void doSomething()
{
super.doSomething();
this.doAnotherthing();
} private void doAnotherthing()
{
System.out.println("功能C");
} }

测试:

 public class Test
{
public static void main(String[] args)
{
Componment componment = new ConcreteComponment(); Componment componment2 = new ConcreteDecorator1(componment); Componment componment3 = new ConcreteDecorator2(componment2); componment3.doSomething(); //功能A }
}

输出结果:

功能A
功能B
功能C

对具体的构建角色进行了“包装”,就实现了更多的功能。到底需要多少包装,我们可以自己决定,体现了动态性和灵活性。

java I/O采用装饰模式实现。

装饰模式用来扩展特定对象的功能,即动态的给对象添加特定的责任(功能),而继承是静态的分配职责,会导致很多子类的产生,缺乏灵活性。