本文共 2808 字,大约阅读时间需要 9 分钟。
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public interface MessageBoardHandler {
-
-
-
- public String filter(String msg);
- }
-
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public class MessageBoard implements MessageBoardHandler {
-
- public String filter(String msg) {
- return "留言板上的内容:" + msg;
- }
- }
-
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public class MessageBoardDecorator implements MessageBoardHandler {
-
- private MessageBoardHandler handler;
- public MessageBoardDecorator(MessageBoardHandler handler) {
- super();
- this.handler = handler;
- }
- public String filter(String msg) {
- return handler.filter(msg);
- }
- }
-
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public class HtmlFilter extends MessageBoardDecorator {
-
- public HtmlFilter(MessageBoardHandler handler) {
- super(handler);
- }
- public String filter(String content) {
- String temp = super.filter(content);
- temp += "^^过滤掉HTML标签!^^";
- return temp;
- }
- }
-
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public class SensitiveFilter extends MessageBoardDecorator {
-
- public SensitiveFilter(MessageBoardHandler handler) {
- super(handler);
- }
- public String filter(String content) {
- String temp = super.filter(content);
- temp += "^^过滤掉政治敏感的字眼!^^";
- return temp;
- }
- }
-
- package com.whatsmars.tomcat.design.decorator;
-
-
-
-
- public class Test {
-
- public static void main(String[] args) {
- MessageBoardHandler mb = new MessageBoard();
- String content = mb.filter("一定要学好装饰模式!");
- System.out.println(content);
-
- mb = new HtmlFilter(new SensitiveFilter(new MessageBoard()));
- content = mb.filter("一定要学好装饰模式!");
- System.out.println(content);
- }
- }
-
- console:
- 留言板上的内容:一定要学好装饰模式!
- 留言板上的内容:一定要学好装饰模式!^^过滤掉政治敏感的字眼!^^^^过滤掉HTML标签!^^
Adapter模式
- package com.whatsmars.tomcat.design.adapter;
-
-
-
-
- public class Adaptee {
-
- public void specificRequest() {
- System.out.println("specific request");
- }
- }
-
- package com.whatsmars.tomcat.design.adapter;
-
-
-
-
- public interface Target {
-
- public void request();
- }
-
- package com.whatsmars.tomcat.design.adapter;
-
-
-
-
- public class Adapter implements Target {
-
- Adaptee adaptee;
-
- public void request() {
- adaptee.specificRequest();
- }
- }
-
- package com.whatsmars.tomcat.design.adapter;
-
-
-
-
- public class Adapter2 extends Adaptee implements Target {
-
- public void request() {
- super.specificRequest();
- }
- }
Facade模式
-- 见
个人认为上述三种模式可以统称Wrapper模式,熟练之后我们不必在意它们究竟属于何种设计模式,当然类的命名最好按具体的模式来。
原文链接:[http://wely.iteye.com/blog/2290854]
转载地址:http://mbgma.baihongyu.com/