vs2005+C#+.net 2.0
using
System;
using System.Collections.Generic;
using System.Text;
namespace SimpleFactoryPattern
... {
public class SchoolUser
...{
protected string FName;
protected string LName;
protected string UserType;
public void Show()
...{
Console.WriteLine("First Name:" + FName);
Console.WriteLine("Last Name:" + LName);
Console.WriteLine("User Type" + UserType);
}
}
public class SchoolPrincipal : SchoolUser
...{
public SchoolPrincipal()
...{
FName = "Jian";
LName = "Yang";
UserType = "Principal";
}
}
public class SchoolTeacher : SchoolUser
...{
public SchoolTeacher()
...{
FName = "David";
LName = "Terry";
UserType = "Teacher";
}
}
public class UserFactory
...{
public SchoolUser GetSchoolUser(string user, string password)
...{
if (user == "Principal" && password == "Principal")
return new SchoolPrincipal();
if (user == "Teacher" && password == "Teacher")
return new SchoolTeacher();
return null;
}
}
class Client
...{
static void Main(string[] args)
...{
UserFactory uf = new UserFactory();
SchoolUser su;
su = uf.GetSchoolUser("Principal", "Principal");
Console.WriteLine("=====Principal Log In=====");
su.Show();
su = uf.GetSchoolUser("Teacher", "Teacher");
Console.WriteLine("======Teacher Log In======");
su.Show();
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace SimpleFactoryPattern
... {
public class SchoolUser
...{
protected string FName;
protected string LName;
protected string UserType;
public void Show()
...{
Console.WriteLine("First Name:" + FName);
Console.WriteLine("Last Name:" + LName);
Console.WriteLine("User Type" + UserType);
}
}
public class SchoolPrincipal : SchoolUser
...{
public SchoolPrincipal()
...{
FName = "Jian";
LName = "Yang";
UserType = "Principal";
}
}
public class SchoolTeacher : SchoolUser
...{
public SchoolTeacher()
...{
FName = "David";
LName = "Terry";
UserType = "Teacher";
}
}
public class UserFactory
...{
public SchoolUser GetSchoolUser(string user, string password)
...{
if (user == "Principal" && password == "Principal")
return new SchoolPrincipal();
if (user == "Teacher" && password == "Teacher")
return new SchoolTeacher();
return null;
}
}
class Client
...{
static void Main(string[] args)
...{
UserFactory uf = new UserFactory();
SchoolUser su;
su = uf.GetSchoolUser("Principal", "Principal");
Console.WriteLine("=====Principal Log In=====");
su.Show();
su = uf.GetSchoolUser("Teacher", "Teacher");
Console.WriteLine("======Teacher Log In======");
su.Show();
Console.Read();
}
}
}
优点:是客户端独立于产品的创建过程,并且在系统引入新产品时无需对客户端进行修改。
缺点:当新产品加入系统时,必须要修改工厂类,已加入必要的处理逻辑。简单工厂模式的致命弱点是处于工厂核心地位的工厂类,一旦它无法确定对哪个类进行实例化,就无法使用模式。