看大话设计模式,记下自己的心得和理解:简单工厂模式和抽象工厂模式相比,区别还是有的,抽象工厂模式很明显地体现出了面向接口编程的思想,《大话设计模式》对抽象工厂的DEMO:
一个User类:
Code
public class User
{
private string _name;
private int _id;
public string Name
{
set { _name = value; }
get { return _name; }
}
public int ID
{
set { _id = value; }
get { return _id; }
}
接着定义两个创建用户的接口:
Code
interface IFactory
{
IUser CreateUser();
}
interface IUser
{
void InsertUser(User user);
User GetUser(int id);
}
接着描述了实现接口的两个类:
Code
class SqlServerFactory:IFactory
{
public IUser CreateUser()
{
return new SqlServerUser();
}
}
class AcessFactory : IFactory
{
public IUser CreateUser()
{
return new AccessUser();
}
}
public class SqlServerUser : IUser
{
public void InsertUser(User user)
{
Console.WriteLine("在SqlServer中给User表插入记录!");
}
public User GetUser(int id)
{
Console.WriteLine("在SqlServer中得到User表的一条记录");
return null;
}
}
public class AccessUser : IUser
{
public void InsertUser(User user)
{
Console.WriteLine("在Access中给User表插入记录!");
}
public User GetUser(int id)
{
Console.WriteLine("在Access中得到User表的一条记录");
return null;
}
}
体现时也很简单:
Code
static void Main(string[] args)
{
User _user = new User();
_user.ID = 1;
_user.Name = "chunchill";
SqlServerFactory sqlFactory = new SqlServerFactory();
IFactory factory = new AcessFactory();
IUser iuser=factory.CreateUser();
iuser.InsertUser(_user);
iuser.GetUser(1);
Console.ReadLine();
}
如想换成ASQLSERVER的创建形式,则方法也非常之简单:
只需改动上面一点点点代码即可:
Code
IFactory factory = new SqlServerFactory();
简单明了的DEMO,不用解释也应该看得出抽象工厂模式的强大功能。也充分体现除了面向接口编程的优势!
方便理解:给出类设计模型图: