简单工厂模式(Simple Factory Pattern)Delphi代码

王朝delphi·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

昨天下午,看完 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操作的部分函数用到了它。

这样就完成了。

如有什么错误,请与联系

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航