设计模式(十)装饰

类结构:

使用装饰模式实现如下需求:

订单列表是主体内容,使用页头、页脚来装饰。

 

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();//打印装饰后的完整订单
	}
}

对象结构:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值