1、简介
装饰者模式又叫包装模式(wrapper),装饰者模式以对客户端透明的方式扩展对象的功能,是继承关系的一种替代方案。
装饰者与被装饰者拥有共同的超类,继承的目的是继承类型,而不是行为。
UML类图

2、装饰者模式的各个角色
2.1、抽象构件角色 :在下面例子中为Human抽象接口,目的是为了规范准备接收附加责任的对象
2.2、具体构件角色 :在下面例子中为Decorator抽象类,这是准备接收附加责任的类
2.3、装 饰 角 色 :在下面例子中为Decorator1、Decorator2
2.4、被 装 饰 角 色:在下面例子中为WhatMe
3、源代码
3.1、抽象构件角色
package Decorator;
/**
* ********************************************************
* @ClassName: Human
* @Description: 抽象构件角色
*
**********************************************************
*/
public interface Human {
public void Say();
}
3.2、具体构件角色
package Decorator;
/**
* ********************************************************
* @ClassName: Decorator
* @Description: 具体构件角色
*
**********************************************************
*/
public abstract class Decorator implements Human{
private Human human;
public Decorator(Human human){
this.human=human;
}
@Override
public void Say() {
human.Say();
}
}
3.3、装饰者1
package Decorator;
/**
* ********************************************************
* @ClassName: Decotator1
* @Description: 装饰角色1
*
**********************************************************
*/
public class Decotator1 extends Decorator{
public Decotator1(Human human) {
super(human);
}
public void woman(){
System.out.println("我是女人");
}
public void Say() {
super.Say();
woman();
}
}
3.4、装饰者2
package Decorator;
/**
* ********************************************************
* @ClassName: Decorator2
* @Description: 装饰者2
*
**********************************************************
*/
public class Decorator2 extends Decorator{
public Decorator2(Human human) {
super(human);
// TODO Auto-generated constructor stub
}
public void person(){
System.out.println("我是人");
}
public void Say() {
super.Say();
person();
}
}
3.5、被装饰者
package Decorator;
/**
* ********************************************************
* @ClassName: WhatMe
* @Description: 被装饰者 可以有一些初始装饰
*
**********************************************************
*/
public class WhatMe implements Human{
public void Say(){
System.out.println("我是什么");
}
}
3.6、测试客户端
package Decorator;
/**
* ********************************************************
* @ClassName: Client
* @Description: 装饰者模式测试类
*
**********************************************************
*/
public class Client {
public static void main(String[] args) {
WhatMe me = new WhatMe();
Decorator decorator = new Decotator1(new Decorator2(me));
decorator.Say();
}
}