1. 程式人生 > >幾年後再倒回來複習 馬士兵老師的責任鏈設計模式實現方式 仍然很經典

幾年後再倒回來複習 馬士兵老師的責任鏈設計模式實現方式 仍然很經典

時隔2年,現在已經從java走向了c# , 複習設計模式的時候想起馬士兵老師的責任鏈實現方式, 太經典了,經典的不是這個鏈的實現,而是他將責任鏈類也實現了介面,這樣鏈本身也是一個Filter,從而可以實現將該類的例項當成Filter新增到該類的例項中。

 

using System;
using System.Collections.Generic;

public interface Filter
{
    String doFilter(String str);
}

public class FilterChain : Filter
{
    List<Filter> filters = new List<Filter>();
    public FilterChain addFilter(Filter f)
    {
        this.filters.Add(f);
        return this;
    }

    public String doFilter(String str)
    {
        String r = str;
        foreach (Filter f in filters)
        {
            r = f.doFilter(r);
        }
        return r;
    }
}

public class HTMLFilter : Filter
{
    public String doFilter(String str)
    {
        String r = str.Replace('<', '[')
                   .Replace('>', ']');
        return r;
    }
}


public class SensitiveFilter : Filter
{
    public String doFilter(String str)
    {
        String r = str.Replace("被就業", "就業")
             .Replace("敏感", "");

        return r;
    }

}

public class FaceFilter : Filter
{
    public String doFilter(String str)
    {
        return str.Replace(":)", "^V^");
    }

}

public class MsgProcessor
{
    public FilterChain Fc { get; set; }
    public string Msg { get; set; }
    public String process()
    {
        return Fc.doFilter(this.Msg);
    }
}

public class Program
{
    static void Main(string[] args)
    {
        String msg = "大家好:),<script>,敏感,被就業,網路授課沒感覺,因為看不見大家夥兒";
        MsgProcessor mp = new MsgProcessor();
        mp.Msg=msg;

        FilterChain fc = new FilterChain().addFilter(new HTMLFilter()).addFilter(new SensitiveFilter());

        FilterChain fc2 = new FilterChain().addFilter(new FaceFilter());
        
        fc.addFilter(fc2);//經典之處,將1個鏈新增到另一個鏈

        mp.Fc=fc;
        String result = mp.process();
        Console.WriteLine(result);//字串非法字元過濾掉的結果
        Console.Read();
    }
}