不定条件的,多条件的过滤删除,显然如果用if...else可以实现可是,现在的要求是实现条件的随意添加,这样的程序,我们怎么样实现灵活的扩展性呢?准备用装饰模式搞一下》代码如下:
定义一个接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
interface IFilterCondition
{
Ware Filter();
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
interface IFilterCondition
{
Ware Filter();
}
}
实现一个条件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class FilterCondition : IFilterCondition
{
private Ware _ware;
public FilterCondition(Ware ware)
{
this._ware = ware;
}
public Ware Filter()
{
if (_ware.Wid == 1)
{
return _ware;
}
return null;
}
}
}
实现第二个条件:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class FilterCondition : IFilterCondition
{
private Ware _ware;
public FilterCondition(Ware ware)
{
this._ware = ware;
}
public Ware Filter()
{
if (_ware.Wid == 1)
{
return _ware;
}
return null;
}
}
}
实现第二个条件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class FilterCondition2:IFilterCondition
{
private Ware _ware;
public FilterCondition2(Ware ware)
{
this._ware = ware;
}
#region IFilterCondition 成员
public Ware Filter()
{
if (_ware.Wname == "1")
{
return _ware;
}
return null;
}
#endregion
}
}
要过滤的实体:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class FilterCondition2:IFilterCondition
{
private Ware _ware;
public FilterCondition2(Ware ware)
{
this._ware = ware;
}
#region IFilterCondition 成员
public Ware Filter()
{
if (_ware.Wname == "1")
{
return _ware;
}
return null;
}
#endregion
}
}
要过滤的实体:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Ware
{
private string wname;
public string Wname
{
get { return wname; }
set { wname = value; }
}
private int wid;
public int Wid
{
get { return wid; }
set { wid = value; }
}
}
}
接下来要过滤了:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Ware
{
private string wname;
public string Wname
{
get { return wname; }
set { wname = value; }
}
private int wid;
public int Wid
{
get { return wid; }
set { wid = value; }
}
}
}
接下来要过滤了:
Ware ware = new Ware();
ware.Wid = 1;
ware.Wname = "1";
IFilterCondition filter = new FilterCondition(ware);
Ware ware3 = new FilterCondition2(filter.Filter()).Filter();
当然代码还有很多的问题,不满足条件会返回nullware.Wid = 1;
ware.Wname = "1";
IFilterCondition filter = new FilterCondition(ware);
Ware ware3 = new FilterCondition2(filter.Filter()).Filter();
相信大家自己能完善吧!