Tar*_*rik 5 .net c# design-patterns
我正在考虑创建一个过滤器对象,过滤和删除上下文中的html标记等所有内容.但我希望它是独立的,这意味着我可以应用的设计模式将帮助我在将来添加更多过滤器而不影响当前代码.我认为抽象工厂,但它似乎不会按我想要的方式工作.也许建设者,但它看起来一样.我不知道我有点困惑,有人请推荐我一个可以解决我的问题的设计模式,但在此之前让我稍微详细说明一下这个问题.
假设我有一个具有描述字段或属性的类.我需要过滤器从这个Description属性中删除我想要的东西.因此,每当我应用过滤器时,我都可以在基础层中添加更多过滤器.因此,我可以轻松添加更多过滤器,而不是重新触摸Description字段,所有过滤器都将针对Description字段运行,并从Description上下文中删除它们应删除的内容.
我希望我可以描述我的问题.我想你们中的一些人之前遇到过同样的情况.
提前致谢...
编辑:
我实际上想要创建过滤器作为类型/类而不是常规方法或其他.喜欢 :
class TextFilter : IFilter
{
private string something;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class HtmlFilter : IFilter
{
private string something;
private string iGotSomething;
public string Awesome {get;set;}
public string FilterYo(string textFiltered)
{
// Do filtering
}
}
class Main
{
protected void Main(object sender, EventArgs e)
{
InputClass input = new InputClass();
string filtered = new StartFiltering().Filter(input.Description); // at this moment, my input class shouldn't know anything about filters or something. I don't know if it makes any sense but this is what in my mind.
}
}
Run Code Online (Sandbox Code Playgroud)
在这一点上,如果我想应用抽象工厂,这将是毫无意义或生成器.因为我不想要一件特别的东西,所以我需要他们所有人.
谢谢你的答案.
编辑2 - 对我来说可能的答案
好吧,让我们考虑使用接口而不是委托来制定战略模式.
interface IFilter //Strategy interface
{
string Filter(string text);
}
class LinkFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter link tags and return pure text;
}
}
class PictureFilter:IFilter //Strategy concrete class
{
public string Filter(string text)
{
//filter links and return pure text;
}
}
class Context
{
private IFilter _filter;
private string _text;
public Context(IFilter filter,string text)
{
this._filter = filter;
this._text = text;
}
public void UpdateFilter(IFilter filter)
{
this._filter = filter;
}
public string RunFilter()
{
this._text = _filter.Filter(this._text);
return this._text;
}
}
class MainProgram
{
static void Main()
{
MyObject obj = new MyObject();
LinkFilter lfilter = new LinkFilter();
PictureFilter pfilter = new PictureFilter();
Context con = new Context(lfilter,obj.Description);
string desc = con.RunFilter();
con.UpdateFilter(pfilter);
desc = con.RunFilter();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么你不重量轻:将过滤器定义为Func<string, string>
.如果你将它们保存在collection(List<Func<string, string>>
)中,你可以这样做:
var text = myObject.DescriptionProperty
foreach (var func in myFuncList)
{
text = func(text);
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用Linq来缩短上面的循环:
var text = myFuncList.Aggregate(text, (seed, func) => func(seed));
Run Code Online (Sandbox Code Playgroud)
这样,您就不必为过滤定义类层次结构.这对环境有好处,因为我们很快就会用完类和命名空间!
为了总结,我建议你继承List:
public class FilterCollection : List<Func<string, string>>
{
public string Filter(string text)
{
return this.Aggregate(text, (seed, func) => func(seed));
}
}
Run Code Online (Sandbox Code Playgroud)