觀察者模式由四個角色組成:抽象組件角色,抽象裝飾者角色,具體組件角色,具體裝飾者角色。
抽象組件角色:給出一個抽象接口,以規范“准備接受附加功能”的對象。
抽象裝飾者角色:持有一個組件(Component)對象的引用,並定義一個與抽象組件接口一致的接口。
具體組件角色:定義一個准備接受附加功能的類。
抽象裝飾者角色:負責給組件對象“貼上”附加的責任。
類圖:

JAVA代碼:
Conponent.java
package com.decorator;
public interface Component
{
void doSomeThing();
}
ConcreteConponent.java
package com.decorator;
public class ConcreteComponent implements Component
{
@Override
public void doSomeThing()
{
System.out.println("功能A");
}
}
Decorator.java
package com.decorator;
public class Decorator implements Component
{
private Component component; //待修飾對象的一個引用
public Decorator(Component component)
{
this.component = component;
}
@Override
public void doSomeThing()
{
this.component.doSomeThing();
}
}
ConcreteDecorator1.java
package com.decorator;
public class ConcreteDecorator1 extends Decorator
{
public ConcreteDecorator1(Component component)
{
super(component);
}
@Override
public void doSomeThing()
{
super.doSomeThing();
doAnotherThing();
}
private void doAnotherThing()
{
System.out.println("功能B");
}
}
ConcreteDecorator2.java
package com.decorator;
public class ConcreteDecorator2 extends Decorator
{
public ConcreteDecorator2(Component component)
{
super(component);
}
@Override
public void doSomeThing()
{
super.doSomeThing();
doAnotherThing();
}
private void doAnotherThing()
{
System.out.println("功能C");
}
}
Test.java
package com.decorator;
public class Test
{
public static void main(String[] args)
{
//ConcreteDecorator1對象裝飾了ConcreteComponent對象
//ConcreteDecorator2對象又修飾了ConcreteDecorator1對象
//在不增加一個同時擁有ConcreteComponent、ConcreteDecorator1和ConcreteDecorator2三個類的功能
//於一身的一個“新的類”的情況下,通過修飾,實現了同時擁有這些功能
Component component = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
component.doSomeThing();
}
}
總結:
裝飾模式以對客戶端透明的方式擴展對象的功能,是繼承關系的一個替代方案,其可以在不創造更多子類的情況下將對象的功能加以擴展。