Main.java
package com.example.decorator;
public class Main {
public static void main(String[] args) {
Response response = new Response();
View head = new View("<title>Hello, world!</title>");
View body = new View("<h1>Hello, world!</h1>");
response.setContent(new HtmlLayout(head, body));
response.render();
}
}Response.java
package com.example.decorator;
public class Response {
private Response content;
public Response () {}
public <T extends Response> void setContent(T content) {
this.content = content;
}
public void render() {
this.content.render();
};
}View.java
package com.example.decorator;
public class View extends Response {
private String content;
public View(String content) {
this.content = content;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
public void render() {
System.out.println(this.content);
}
}Layout.java
package com.example.decorator;
public class Layout extends Response {
private Response view;
public <T extends Response> Layout(T view) {
this.view = view;
}
public void render() {
this.view.render();
}
}HtmlLayout.java
package com.example.decorator;
public class HtmlLayout extends Response {
private Response head;
private Response body;
public <T extends Response> HtmlLayout(T head, T body) {
this.head = head;
this.body = body;
}
public void render() {
System.out.println("<!doctype html>");
System.out.println("<html>");
System.out.println("<head>");
this.head.render();
System.out.println("</head>");
System.out.println("<body>");
this.body.render();
System.out.println("</body>");
System.out.println("</html>");
}
}发布于 2011-06-04 09:21:43
当您希望类型(接口)A的对象执行比当前更多的操作时,可以使用装饰器模式。例如:适合您物理屏幕的Web页面(逻辑屏幕)不需要滚动条。但是,如果页面(逻辑屏幕)不适合物理屏幕,则必须使用滚动条来装饰它。用GOF的话说: Decorator的目的是动态地将额外的责任附加到对象上。
在下面这样的代码中:
interface LogicalScreen {
void render(String physical );
}一个实现:
class SimpleScreen implements LogicalScreen {
public void render(String physical) {
// render itself
}
}装饰器的实现:
class ScreenWithScrollbar implements LogicalScreen {
private final LogicalScreen decoratd;
public ScreenWithScrollbar(LogicalScreen decorated) {
this.decoratd = decorated;
}
public void render(String physical) {
// render scroll bar
// ...
// render the decorated
decoratd.render(physical);
// eventually do some more stuff
}
public doScroll() {}
}如何连线:
public class WhatIsDecorator {
public static void main(String[] args) {
LogicalScreen l1 = new SimpleScreen();
LogicalScreen ds = new ScreenWithScrollbar(l1);
ds.render("MyMonitor");
}
}你可以像这样链接你需要的任何数量。Decorator2(Decorator1(简单)) ...
发布于 2011-06-04 05:29:22
据我所知,简而言之:
诚挚的问候
https://stackoverflow.com/questions/6232769
复制相似问题