TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1、定义及作用 该模式以对客户端透明的方式扩展对象的功能。 2、涉及角色
抽象构件角色:定义一个抽象接口,来规范准备附加功能的类。 具体构件角色:将要被附加功能的类,实现抽象构件角色接口。 抽象装饰者角色:持有对具体构件角色的引用并定义与抽象构件角色一致的接口。 具体装饰角色:实现抽象装饰者角色,负责为具体构件添加额外功能。
3、简单实现
抽象构件角色java 代码
package decorator;
/**
* 装饰者和原组建的共同方法接口(抽象构件角色)
* @author mouca.he
*
*/
public interface InterfaceComponent {
/**
* 组件方法 say()
*
*/
public void say();
}
具体构件角色java 代码
package decorator;
/**
* 原组件(具体构件角色)
* @author mouca.he
*
*/
public class Component implements InterfaceComponent{
public void say() {
// TODO 自动生成方法存根
System.out.println("Component.say():原组件的方法!");
}
}
抽象装饰者角色java 代码
package decorator;
/**
* 抽象装饰者
* @author mouca.he
*
*/
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();
};
}
具体装饰者二java 代码
package decorator;
/**
* 装饰者二
* @author mouca.he
*
*/
public class DecoratorTwo extends AbstractDecorator{
public DecoratorTwo(InterfaceComponent component) {
super(component);
// TODO 自动生成构造函数存根
}
/**
* 根据需要重载模板类preSay()方法
*/
protected void preSay(){
System.out.println("DecoratorTwo.preSay():装饰者二的preSay()方法!");
}
/**
* 根据需要重载模板类afterSay()方法
*/
protected void afterSay(){
System.out.println("DecoratorTwo.afterSay():装饰者二的afterSay()方法!");
}
}
装饰者一java 代码
package decorator;
/**
* 装饰者一
* @author mouca.he
*
*/
public class DecoratorOne extends AbstractDecorator{
public DecoratorOne(InterfaceComponent component) {
super(component);
// TODO 自动生成构造函数存根
}
/**
* 根据需要重载模板类preSay()方法
*/
protected void preSay(){
System.out.println("DecoratorOne.preSay():装饰者一的preSay()方法!");
}
/**
* 根据需要重载模板类afterSay()方法
*/
protected void afterSay(){
System.out.println("DecoratorOne.afterSay():装饰者一的afterSay()方法!");
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
InterfaceComponent interfaceComponent = new DecoratorTwo(new DecoratorOne(new Component()));
interfaceComponent.say();
/*
* 控制台输出:
* DecoratorTwo.preSay():装饰者二的preSay()方法!
* DecoratorOne.preSay():装饰者一的preSay()方法!
* Component.say():原组件的方法!
* DecoratorOne.afterSay():装饰者一的afterSay()方法!
* DecoratorTwo.afterSay():装饰者二的afterSay()方法!
*/
}
}
4、优缺点 优点:1)提供比继承更多的灵活性 2)使用不同的装饰组合可以创造出不同行为的组合 3)需要的类的数目减少 缺点:1)灵活性带来比较大的出错性 2)产生更多的对象,给查错带来困难
源码下载:http://file.javaxxz.com/2014/11/5/000202843.zip |
|