装饰模式实例
装饰模式实例
- 问题描述
- 结构图
- 编程实现
- Table类(被装饰者)
- 抽象装饰者类
- 具体装饰者类
- 客户端
问题描述
在某OA系统中提供一个报表生成工具,用户可以通过该工具为表格增加表头和表尾,允许用户为报表增加多个不同的表头和表尾,用户还可以自行确定表头和表尾的次序,为了能够灵活的设置表头和表尾的次序并且易于增加表头和表尾。
结构图

编程实现
Table类(被装饰者)
public class Table {private int rowNum;private int colNum;private String description;public int getRowNum() {return rowNum;}public void setRowNum(int rowNum) {this.rowNum = rowNum;}public int getColNum() {return colNum;}public void setColNum(int colNum) {this.colNum = colNum;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}
}
抽象装饰者类
public abstract class Decorator {protected Table table;public abstract void addHeader(Table table);public abstract void addTail(Table table);
}
具体装饰者类
public class TableDecoratorA extends Decorator{@Overridepublic void addHeader(Table table) {System.out.println("TableDecoratorA addHeader");}@Overridepublic void addTail(Table table) {System.out.println("TableDecoratorA addTail");}
}
public class TableDecoratorB extends Decorator{@Overridepublic void addHeader(Table table) {System.out.println("TableDecoratorB addHeader");}@Overridepublic void addTail(Table table) {System.out.println("TableDecoratorB addHeader");}
}
客户端
public class Client {public static void main(String[] args) {Decorator decorator=new TableDecoratorA();Table table=new Table();decorator.addHeader(table);decorator.addTail(table);}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
