装饰者模式
装饰者模式的好处是便于扩展,对一个东西不管怎么变,只需要找到相应的组件去改变它
1.如何组装在一起:
创建主题:
PacketBodyCreator body = new PacketBodyCreator();
创建header
PacketHTMLHeaderCreator html = new PacketHTMLHeaderCreator(body);
创建HTTP头:
PacketHTTPHeaderCreator httpHeader = new PacketHTTPHeaderCreator(html);
组件组装成功,调用组装方法输出:
httpHeader. handleContent();
2.详细分解调用组装的过程为:
(1).在PacketBodyCreator, PacketHTMLHeaderCreator, PacketHTTPHeaderCreator中都有handleContent方法,
(2).httpHeader. handleContent();首先进行第一次组装时发现HTML还没组装呢,就去组装HTML,组装HTML时发现正文body还没组装呢,就去租住body,
(3).body组装完了,终于可以组装html了,html组装完了终于可以组装HTTP头了,然后可以输出了
3.具体代码如下:
public interface IPacketCreator {
/**
* @return
* 用于内容处理
*/
public String handleContent();
}
public class PacketBodyCreator implements IPacketCreator {
@Override
public String handleContent() {
return "Content of Packet";
}
}
public abstract class PacketDecorator implements IPacketCreator {
IPacketCreator component;
public PacketDecorator(IPacketCreator component) {
super();
this.component = component;
}
}
public class PacketHTMLHeaderCreator extends PacketDecorator {
public PacketHTMLHeaderCreator(IPacketCreator component) {
super(component);
}
@Override
public String handleContent() {
StringBuffer sb = new StringBuffer();
sb.append("<html>");
sb.append("<body>");
sb.append(component.handleContent());
sb.append("</body>");
sb.append("</html>\n");
return sb.toString();
}
}
public class PacketHTTPHeaderCreator extends PacketDecorator {
public PacketHTTPHeaderCreator(IPacketCreator component) {
super(component);
}
@Override
public String handleContent() {
StringBuffer sb = new StringBuffer();
sb.append("cache-Contorl:noche\n");
sb.append("Date:Mon,31Dec201204:25:57GMT\n");
sb.append(component.handleContent());
return sb.toString();
}
}