1.具体操作类
namespace Data
{
/// <summary>
/// 此操作代表对数据库的增,删,改操作的基类
/// </summary>
public class OperateDB
{
public virtual string OperateData()
{
string result = null;
return result;
}
}
/// <summary>
/// 添加数据类
/// </summary>
public class InsertDB : OperateDB
{
public override string OperateData()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = new Employees();
e.LastName = "yoyozhu";
e.FirstName = "zhushao";
db.AddToEmployees(e);
db.SaveChanges();
return "添加数据成功";
}
}
/// <summary>
/// 删除数据类
/// </summary>
public class DelDB : OperateDB
{
public override string OperateData()
{
NorthwindEntities db = new NorthwindEntities();
Employees e=db.Employees.Where(c=>c.EmployeeID==19).FirstOrDefault();
db.DeleteObject(e);
db.SaveChanges();
return "删除数据成功";
}
}
/// <summary>
/// 修改数据类
/// </summary>
public class UpdateDB : OperateDB
{
public override string OperateData()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = db.Employees.Where(c => c.EmployeeID == 19).FirstOrDefault();
e.LastName = "chuanshi_yoyo";
db.SaveChanges();
return "修改数据成功";
}
}
}
2.工厂类
namespace Data
{
public interface IOperateFactory
{
OperateDB CreateOperateDB();
}
public class InsertFactory : IOperateFactory
{
#region IOperateFactory 成员
public OperateDB CreateOperateDB()
{
return new InsertDB();
}
#endregion
}
public class UpdateFactory : IOperateFactory
{
#region IOperateFactory 成员
public OperateDB CreateOperateDB()
{
return new UpdateDB();
}
#endregion
}
public class DelFactory : IOperateFactory
{
#region IOperateFactory 成员
public OperateDB CreateOperateDB()
{
return new DelDB();
}
#endregion
}
}
3.客户端调用
static void Main(string[] args)
{
/*和简单工厂相比,不同之处在于选择哪个具体的类来操作数据,
*简单工厂是放在服务端,工厂方法是放在调用端,都要去选择
*哪一个具体类来进行实际的操作。这一点,不如策略模式强
*/
IOperateFactory operate = new InsertFactory();
OperateDB db = operate.CreateOperateDB();
Console.WriteLine(db.OperateData());
Console.ReadKey();
}