最近在学习设计模式,今天用解释器模式做了一个过滤HTML字符的小应用。代码如下:
AbstractExpression类
public abstract class AbstractExpression
{
protected string strKeyword;
/// <summary>
/// 过滤
/// </summary>
/// <param name="context"></param>
public abstract void Filter(Context context);
/// <summary>
/// 获取关键字字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
protected abstract string GetKeywordString(string str);
}
Context类
public class Context
{
public Context(string str)
{
FilterString = str;
}
/// <summary>
/// 要过滤的字符串
/// </summary>
public string FilterString
{
get;
set;
}
}
HtmlExpression类
public class HtmlExpression : AbstractExpression
{
public HtmlExpression(string _Keyword)
{
strKeyword = _Keyword;
}
public override void Filter(Context context)
{
if (strKeyword.Length == 0)
return;
string str1 = "a";
while (str1.Length > 0)
{
str1 = GetKeywordString(context.FilterString);
if (str1.Length > 0)
context.FilterString = context.FilterString.Replace(str1, string.Empty);
}
context.FilterString = context.FilterString.Replace(string.Format("</{0}>", strKeyword), string.Empty);
}
protected override string GetKeywordString(string str)
{
int start = str.IndexOf(string.Format("<{0}", strKeyword));
if (start < 0)
return string.Empty;
int end = str.IndexOf(">", start);
return str.Substring(start, end - start + 1);
}
}
调用
private void 过滤ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (rtxt1.Text.Length == 0)
return;
Context context = new Context(rtxt1.Text.ToLower());
ArrayList list = new ArrayList();
list.Add(new HtmlExpression("div"));
list.Add(new HtmlExpression("td"));
list.Add(new HtmlExpression("tr"));
list.Add(new HtmlExpression("th"));
list.Add(new HtmlExpression("table"));
list.Add(new HtmlExpression("span"));
list.Add(new HtmlExpression("html"));
list.Add(new HtmlExpression("body"));
list.Add(new HtmlExpression("form"));
list.Add(new HtmlExpression("select"));
list.Add(new HtmlExpression("option"));
list.Add(new HtmlExpression("a"));
list.Add(new HtmlExpression("ul"));
list.Add(new HtmlExpression("li"));
list.Add(new HtmlExpression("h1"));
list.Add(new HtmlExpression("h2"));
list.Add(new HtmlExpression("h3"));
list.Add(new HtmlExpression("h4"));
list.Add(new HtmlExpression("h5"));
list.Add(new HtmlExpression("head"));
list.Add(new HtmlExpression("title"));
list.Add(new HtmlExpression("img"));
list.Add(new HtmlExpression("strong"));
list.Add(new HtmlExpression("p"));
list.Add(new HtmlExpression("em"));
list.Add(new HtmlExpression("b"));
list.Add(new JavaScriptExpression("script"));
list.Add(new JavaScriptExpression("style"));
list.Add(new HtmlExpression("font"));
list.Add(new NoteExpression());
list.Add(new OtherExpression("br"));
list.Add(new OtherExpression("meta"));
list.Add(new OtherExpression("input"));
foreach (AbstractExpression exp in list)
{
exp.Filter(context);
}
rtxt2.Text = context.FilterString;
}