工厂模式
- 存在一个创建对象的工厂
- 调用者从中取得特别的对象
- 由工厂决定如何符合调用需求
- 客户不知道对象如何生成
应用示列(一)
{
public enum UserType { Employee = 0, Sales = 1, Guest = 2 }
public class User
{
protected string mPermissionLevel = "Z";
public string GetPermissionLevel()
{
return mPermissionLevel;
}
}
public class Employee : User
{
public Employee()
{
mPermissionLevel = "A";
}
}
public class Sales : User
{
public Sales()
{
mPermissionLevel = "B";
}
}
public class Guest : User
{
public Guest()
{
mPermissionLevel = "C";
}
}
//工厂类
public class FactoryCreater
{
public FactoryCreater() { }
public static User CreateUser(UserType userType)
{
User u;
switch (userType)
{
case UserType.Employee:
u = new Employee();
break;
case UserType.Sales:
u = new Sales();
break;
case UserType.Guest:
u = new Guest();
break;
default:
u = new User();
break;
};
return u;
}
static void Main(string[] args)
{
Console.WriteLine("请输入使用者类型{0,1,2}");
UserType t = (UserType)int.Parse(Console.ReadLine());
User newUser = FactoryCreater.CreateUser(t);
Console.WriteLine("建立了{0}对象", newUser.ToString());
Console.WriteLine("权限等级={0}", newUser.GetPermissionLevel());
}
}
}
应用示例(二)
{
//名字工厂类
public class NameFactory
{
public NameFactory() { }
public Namer getName(string name)
{
int i = name.IndexOf(",");
if (i > 0)
return new LastFirst(name);
else
return new FirstFirst(name);
}
}
{
//parts stored here
protected string frName, lName;
//return first name
public string getFrname()
{
return frName;
}
//return last name
public string getLname()
{
return lName;
}
}
public class FirstFirst : Namer
{
public FirstFirst(string name)
{
int i = name.IndexOf(" ");
if (i > 0)
{
frName = name.Substring(0, i).Trim();
lName = name.Substring(i + 1).Trim();
}
else
{
lName = name;
frName = "";
}
}
}
public class LastFirst : Namer
{
public LastFirst(string name)
{
int i = name.IndexOf(",");
if (i > 0)
{
lName = name.Substring(0, i);
frName = name.Substring(i + 1).Trim();
}
else
{
lName = name;
frName = "";
}
}
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:.NET常用设计模式——工厂模式 - Python技术站