1.模板类
namespace Data
{
/* 模板模式:其实就是抽象出各个具体操作类的公共操作方法,在子类重新
* 实现,然后使用子类去实例化父类。这个模板类其实可以使用接口替换。事
* 实上接口才是专门用来定义操作规范。当然,当有些公共方法,各个子类
* 均有一致需求,此时就不应使用接口,使用抽象类
*/
public abstract class TemplateClass
{
public abstract string InsertDB();
public abstract string UpdateDB();
public abstract string DelDB();
}
public class OperateCustomers : TemplateClass
{
public override string InsertDB()
{
NorthwindEntities db = new NorthwindEntities();
Customers e = new Customers();
e.CompanyName = "chuanshi_yoyo_yoyo";
e.ContactName = "zhushao";
db.AddToCustomers(e);
db.SaveChanges();
return "添加数据成功\n";
}
public override string UpdateDB()
{
NorthwindEntities db = new NorthwindEntities();
Customers e = db.Customers.Where(c => c.CustomerID == "AFTER").FirstOrDefault();
e.ContactName = "yo_shao";
db.SaveChanges();
return "修改数据成功\n";
}
public override string DelDB()
{
NorthwindEntities db = new NorthwindEntities();
Customers e = db.Customers.Where(c => c.CustomerID == "AFTER").FirstOrDefault();
db.DeleteObject(e);
db.SaveChanges();
return "删除数据成功\n";
}
}
public class OperateEmployees : TemplateClass
{
public override string InsertDB()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = new Employees();
e.LastName = "chuanshi_yoyo_yoyo";
e.FirstName = "zhushao";
db.AddToEmployees(e);
db.SaveChanges();
return "添加数据成功\n";
}
public override string UpdateDB()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = db.Employees.Where(c => c.EmployeeID == 42).FirstOrDefault();
e.LastName = "yo_shao";
db.SaveChanges();
return "修改数据成功\n";
}
public override string DelDB()
{
NorthwindEntities db = new NorthwindEntities();
Employees e = db.Employees.Where(c => c.EmployeeID == 42).FirstOrDefault();
db.DeleteObject(e);
db.SaveChanges();
return "删除数据成功\n";
}
}
}
2.调用
static void Main(string[] args)
{
TemplateClass template = new OperateEmployees();
Console.WriteLine(template.InsertDB());
Console.ReadKey();
}