昨天下午,看完 guoyan19811021 的设计模式之简单工厂模式(Simple Factory Pattern)(参见http://www.csdn.net/Develop/read_article.asp?id=26635) 之后,为了加深印象,我把上面的VB.Net改成了Delphi,未必有很大的意义,但还是贴出来,与大家共享。
首先建一个基类 CName,如下
type
CName= Class
private
{ Public declarations }
public
{ protected declarations}
function getFirstName:string;
function getLastName:string;
protected
{ Private declarations }
m_sFirstName:string;
m_sLastName:string;
end;
下面是2个继承类
type
CFirst001= Class(CName)
public
{ Public declarations }
constructor Create(a_sInput:string);
protected
{ protected declarations}
private
{ Private declarations }
end;
type
CFirst002 = Class(CName)
public
{ Public declarations }
constructor Create(a_sInput:string);
protected
{ protected declarations}
private
{ Private declarations }
end;
简单工厂类
type
CNameFactory = Class
public
{ Public declarations }
function getName(a_sInput:string):CName;
protected
{ Protected declarations }
private
{ Private declarations }
end;
以下是各个函数的实现部分
function CName.getFirstName:string;
Begin
result := m_sFirstName;
End;
function CName.getLastName:string;
Begin
result := m_sLastName;
End;
constructor CFirst001.Create(a_sInput:string);
var i:integer;
Begin
inherited Create;
//Add code here
i := Pos(' ',a_sInput);
if(i > 0) then begin //can find the ' '(space)
m_sFirstName := Copy(a_sInput,1,i - 1);
m_sFirstName := Trim(m_sFirstName);
m_sLastName := Copy(a_sInput,i + 1,Length(a_sInput) - i);
m_sLastName := Trim(m_sLastName);
end
else begin //can't find the ' '(space)
m_sFirstName := '';
m_sLastName := a_sInput;
end;
End;
constructor CFirst002.Create(a_sInput:string);
var
i,j:integer;
Begin
inherited Create;
//Add code here
i := Pos(',',a_sInput);
if(i > 0) then begin //can find the ' '(space)
m_sFirstName := Copy(a_sInput,1,i - 1);
m_sFirstName := Trim(m_sFirstName);
m_sLastName := Copy(a_sInput,i + 1,Length(a_sInput) - i);
m_sLastName := Trim(m_sLastName);
end
else begin //can't find the ' '(space)
m_sFirstName := '';
m_sLastName := a_sInput;
end;
End;
function CNameFactory.getName(a_sInput:string):CName;
var i:integer;
Begin
i := Pos(',',a_sInput);
if(i > 0) then
begin
result := CFirst002.Create(a_sInput);
end
else begin
result := CFirst001.Create(a_sInput);
end;
End;
当然,仅仅这样是不能够运行的,还需要在interface 部分加上uses
Sysutils;因为string操作的部分函数用到了它。
这样就完成了。
如有什么错误,请与我联系