这个例子主要是用来根据用户录入的“FirstName LastName”和“LastName,FirstName”两种可能的姓名来获得FirstName和LastName。父类是Namer,子类是FirstFirst,LastFirst,简单的工厂类是NamerFact,具体的代码如下:
namespace GoFClass
{
//父类
public class Namer
{
protected string strFirstName;
protected string strLastName;
public string getFirstName()
{
return strFirstName;
}
public string getLastName()
{
return strLastName;
}
}
//以下是两个派生类
public class FirstFirst:Namer
{
public FirstFirst(string strName)
{
int i=strName.Trim().IndexOf(" ");
if(i>0)
{
strFirstName=strName.Substring(0,i).Trim();
strLastName=strName.Substring(i+1).Trim();
}
else
{
strFirstName="";
strLastName=strName;
}
}
}
public class LastFirst:Namer
{
public LastFirst(string strName)
{
int i=strName.Trim().IndexOf(",");
if(i>0)
{
strLastName=strName.Substring(0,i).Trim();
strFirstName=strName.Substring(i+1).Trim();
}
else
{
strFirstName="";
strLastName=strName;
}
}
}
//简单工厂类
public class NameFactory
{
public NameFactory()
{
}
public Namer getName(string strName)
{
int i=strName.Trim().IndexOf(" ");
if(i>0)
return new FirstFirst(strName);
else
return new LastFirst(strName);
}
}
}
//使用方法
NameFactory nameFac=new NameFactory();
Namer namer=nameFac.getName(tbName.Text);
tbFirstName.Text=namer.getFirstName();
tbLastName.Text=namer.getLastName();