您的位置:首页 > 其它

设计模式之装饰模式实例

2015-01-19 11:04 253 查看
装饰模式可以动态地给一个对象添加一些额外的职责。比子类更加灵活。装饰模式可以无需创建子类的情况下扩展类的功能。下面通过一个打印发票的例子来说明。发票分为三个部分:头部,主体,尾部。而主体不变,头和尾确是不一样的。下面说明。
首先是客户端使用的接口
IPrintable接口
public interface IPrintable{
public void print();
}
设计一个可以供客户端使用的实现类:
Order发票打印类
public class Order implements IPrintable{
public void print(){
System.out.println("发票的主体部分");
}
}
下面是装饰类。

OrderDecorator抽象类
public abstract class OrderDecorator implements IPrintable{
private IPrintable printable;
public OrderDecorator(IPrintable printable){
super();
this.printable=printable;
}

@Override
public void print(){
printable.print();
}
}
HeaderDecorator装饰类
public class HeaderDecorator extends OrderDecorator{
public HeaderDecorator(IPrintable printable){
super(printable);
}

@Override
public void print(){
System.out.println("发票头部");
super.print();
}
}
FooterDecorator装饰类
public class FooterDecorator extends OrderDecorator{
public FooterDecorator(IPrintable printable){
super(printable);
}

@Override
public void print(){
super.print();
System.out.println("发票尾部");
}
}
客户端代码如下
Client类
public class Client{
public static void main(String[] args){
//测试原始类
IPrintable order=new Order();
order.print();
System.out.println("-----打印完毕-----");

//测试装饰头部的类
IPrintable headerOrder=new HeaderDecorator(new Order());
headerOrder.print();
System.out.println("-----打印完毕-----");

//厕所装饰头部和尾部的类
IPrintable headerAndFooterOrder=new HeaderDecorator(new FooterDecorator(new Order()));
headerAndFooterOrder.pritn();
System.out.println("-----打印完毕-----");
}
}
这是装饰模式的典型用法,看起来像是把一个对象一层一层包装起来一样。这也正是装饰模式的别名“包装器”的由来。
运行结果如下:
发票的主体部分

-----打印完毕-----
发票头部
发票的主体部分

-----打印完毕-----
发票头部发票的主体部分
发票尾部-----打印完毕-----

(end)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: