这是一个过滤消息的例子。
==========================
package com.fullwisdom.moden.chain;
public class Message {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
=========================
package com.fullwisdom.moden.chain;
public interface Handler {
public Message doFilter(Message message);
}
=========================
package com.fullwisdom.moden.chain;
public class HTMLHandler implements Handler {
@Override
public Message doFilter(Message message) {
String msg = message.getContent();
msg = msg.replaceAll("<", "<");
msg = msg.replaceAll(">", ">");
message.setContent(msg);
return message;
}
}
==============================
package com.fullwisdom.moden.chain;
public class SensitiveHandler implements Handler {
@Override
public Message doFilter(Message message) {
String msg = message.getContent().replaceAll("我日", "**").replaceAll("我操", "**");
message.setContent(msg);
return message;
}
}
=================================
package com.fullwisdom.moden.chain;
import java.util.ArrayList;
import java.util.List;
public class Chain implements Handler {
List<Handler> list = new ArrayList<Handler>();
public void addHandler(Handler handler){
this.list.add(handler);
}
@Override
public Message doFilter(Message message) {
for(Handler h :list)
message = h.doFilter(message);
return message;
}
}
===============================
public class Main{
public stiatic void main(String[] args){
String content = "<H1>我日</H1><H1>我日</H1><H1>我日</H1><H1>我操 hello 。。 fuck</H1><H1>我日</H1>";
Message message= new Message();
message.setContent(content);
HTMLHandler htmlHandler = new HTMLHandler();
SensitiveHandler sensitiveHanler = new SensitiveHandler();
Chain chain = new Chain();
chain.addHandler(htmlHandler);
chain.addHandler(sensitiveHanler);
message = chain.doFilter(message);
System.out.println(message.getContent());
}
}