前言
滤液器模式可以很方便地实现对一个列表中的元素进行过滤的功能,能方便地修改滤器的现实,符合开闭原则。
代码
csharp
//过滤接口
public interface IFilter
{
List<RefuseSorting> Filter(List<RefuseSorting> refuseList);
}
//垃圾分类
public class RefuseSorting
{
private string _name;
private string _type;
public RefuseSorting(string name, string type)
{
_name = name;
_type = type;
}
public string Name { get { return _name; } }
public string Type { get { return _type; } }
}
//按名称过滤器
public class NameFilter : IFilter
{
private string name;
public NameFilter(string name) { this.name = name; }
public List<RefuseSorting> Filter(List<RefuseSorting> refuseList)
{
List<RefuseSorting> refuseFilters = new List<RefuseSorting>();
foreach (RefuseSorting filter in refuseList)
{
if (filter.Name.Equals(name))
{
refuseFilters.Add(filter);
}
}
return refuseFilters;
}
}
//按类型过滤器
public class TypeFilter : IFilter
{
private string type;
public TypeFilter(string type)
{
this.type = type;
}
public List<RefuseSorting> Filter(List<RefuseSorting> refuseList)
{
List<RefuseSorting> refuseFilters = new List<RefuseSorting>();
foreach (RefuseSorting filter in refuseList)
{
if (filter.Type.Equals(type))
{
refuseFilters.Add(filter);
}
}
return refuseFilters;
}
}
internal class Program
{
/*
* 结构型模式:Structural Pattern
* 过滤器模式:Filter Pattern
*/
static void Main(string[] args)
{
//创建列表
List<RefuseSorting> filters = new List<RefuseSorting>();
filters.Add(new RefuseSorting("矿泉水瓶" , "可回收垃圾"));
filters.Add(new RefuseSorting("废弃纸箱" , "可回收垃圾"));
filters.Add(new RefuseSorting("厕纸", "不可回收垃圾"));
filters.Add(new RefuseSorting("卫生纸", "不可回收垃圾"));
filters.Add(new RefuseSorting("鱼骨头", "厨余垃圾"));
filters.Add(new RefuseSorting("果核", "厨余垃圾"));
filters.Add(new RefuseSorting("过期化妆品", "有害垃圾"));
//创建过滤器
IFilter recoverableTypeFilter = new TypeFilter("可回收垃圾");
IFilter nameFilter = new NameFilter("过期化妆品");
// 按类型进行过滤操作
List<RefuseSorting> refuseTypeFilters = recoverableTypeFilter.Filter(filters);
Console.WriteLine("Filtered refuse (Type):");
PrintList(refuseTypeFilters);
// 按名称进行过滤操作
List<RefuseSorting> refuseNameFilters = nameFilter.Filter(filters);
Console.WriteLine("Filtered refuse (Name):");
PrintList(refuseNameFilters);
Console.ReadLine();
}
//打印集合
public static void PrintList(List<RefuseSorting> refuseList)
{
foreach (RefuseSorting filter in refuseList)
{
Console.WriteLine($"{filter.Name},{filter.Type}");
}
}
}