类结构:
使用装饰模式实现如下需求:
订单列表是主体内容,使用页头、页脚来装饰。
1、抽象组件
public abstract class OrderElement {
public abstract void print();
}
2、主体组件
import java.util.Vector;
public class OrderList extends OrderElement {
protected Vector<OrderItem> orderItems = new Vector<OrderItem>();
@Override
public void print() {
for (int i = 0; i < orderItems.size(); i++) {
OrderItem orderItem = orderItems.get(i);
orderItem.print();
}
}
public void addItem(OrderItem item) {
orderItems.add(item);
}
public void removeItem(OrderItem item) {
orderItems.remove(item);
}
public double getTotal() {
double total = 0;
for (int i = 0; i < orderItems.size(); i++) {
OrderItem item = orderItems.get(i);
total += item.getSubtotal();
}
return total;
}
}
3、抽象装饰
public abstract class OrderDecorator extends OrderElement {
protected OrderElement element;
public OrderDecorator(OrderElement element) {
this.element = element;
}
}
4、具体装饰
public class HeaderDecorator extends OrderDecorator {
public HeaderDecorator(OrderElement element) {
super(element);
}
@Override
public void print() {
printHeader();//增加打印头信息的功能
element.print();
}
private void printHeader() {
System.out.println("===================================================");
System.out.println("商品\t数量\t价格\t小计");
System.out.println("---------------------------------------------------");
}
}
public class FooterDecorator extends OrderDecorator {
public FooterDecorator(OrderElement element) {
super(element);
}
@Override
public void print() {
element.print();
printFooter();//增加打印脚信息的功能
}
private void printFooter() {
System.out.println("---------------------------------------------------");
System.out.println("总价\t\t\t"+ ((OrderList)element).getTotal());
System.out.println("===================================================");
}
}
5、主体组件里的小项(订单列表里的单个商品项)
public class OrderItem {
private String name;
private int units;
private double price;
public OrderItem(String name, int units, double price) {
this.name = name;
this.units = units;
this.price = price;
}
public void print() {
System.out.println(name + "\t" + units + "\t" + price + "\t" + getSubtotal());
}
public double getSubtotal() {
return price * units;
}
}
6、消费者
public class Customer {
public static void main(String[] args) {
OrderList orderList = new OrderList();//订单列表
OrderItem orderItem1 = new OrderItem("轮胎",4,154);
OrderItem orderItem2 = new OrderItem("挡泥板",2,300);
orderList.addItem(orderItem1);//添加一项商品
orderList.addItem(orderItem2);//添加一项商品
OrderElement element = new HeaderDecorator(new FooterDecorator(orderList));//使用页头、页脚装饰订单列表
element.print();//打印装饰后的完整订单
}
}
对象结构: