最近在学习设计模式,每个模式都是前人经验的传承,是经过总结形成的一套某一类问题的一般性解决方案,说这些其实是有目的的,呵呵不跟大家卖关子了,言归正传,我是为了说接口的重要性的,我认为设计模式非常重要,所以其常用的就更重要了,最近学习设计模式的时候总是遇到接口,抽象类,这个模式是抽象类,那个模式是接口,弄的我迷迷糊糊的,决定认真研究一下,下面就跟大家分享一下我研究的结果吧,希望大家多提意见
什么是接口?
如何使用接口?
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 用了抽象模式的数据访问程序{ class Program { static void Main(string[] args) { User user = new User(); Department dept = new Department(); //Ifactory factory =new SqlserverFactory(); IFactory factory = new AccessFactory(); //此时已经与具体的数据库访问解除了依赖 IUser iu = factory.CreateUser(); iu.Insert(user); iu.GetUser(1); IDepartment id = factory.CreateDepartment(); id.Insert(dept); id.GetDepartment(1); Console.Read(); } } class User { private int id; public int ID { get { return id; } set { id = value; } } } class Department { private int id; public int ID { get { return id; } set { id = value; } } } //IDepartment接口,用于客户端访问,解除与具体数据库访问的耦合。 interface IDepartment { void Insert(Department department); Department GetDepartment(int id); } //SqlserverDepartment类,用于访问SQL Server的Department class SqlserverDepartment : IDepartment { public void Insert(Department department) { Console.WriteLine("在SQL Server 中给Department表增加一条记录"); } public Department GetDepartment(int id) { Console.WriteLine("在SQL Server 中根据ID得到Department表一条记录"); return null; } } //Access类,用于访问Access的Department class AccessDepartment : IDepartment { public void Insert(Department department) { Console.WriteLine("在Access 中给Department表增加一条记录"); } public Department GetDepartment(int id) { Console.WriteLine("在Access中根据ID得到Department表一条记录"); return null; } } //IUser接口,用于客户端访问,解除与具体数据库访问的耦合 interface IUser { void Insert(User user); User GetUser(int id); } //SqlserverUser类,用于访问SQL Server的User class SqlserverUser : IUser { public void Insert(User user) { Console.WriteLine("在SQL Server 中给User表增加一条记录"); } public User GetUser(int id) { Console.WriteLine("在SQL Server中根据ID得到User表一条记录"); return null; } } //Access类,用于访问Access的User class AccessUser : IUser { public void Insert(User user) { Console.WriteLine("在Access中给User表增加一条记录"); } public User GetUser(int id) { Console.WriteLine("在Access中根据得到User表一条记录"); return null; } } //IFactory 接口,定义一个创建访问Department表对象的抽象的工厂接口 interface IFactory { IUser CreateUser(); //增加的接口方法 IDepartment CreateDepartment(); } //SqlServerFactory类,实现IFactory接口,实例化SqlserverUser和SqlserverDepartment class SqlserverFactory : IFactory { public IUser CreateUser() { return new SqlserverUser(); } public IDepartment CreateDepartment() { return new SqlserverDepartment(); } } //AccessFactory类,实现IFactory接口,实例化AccessUser和AccessDepartment class AccessFactory : IFactory { public IUser CreateUser() { return new AccessUser(); } public IDepartment CreateDepartment() { return new AccessDepartment(); } }}