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

作者看完简单工厂模式的VB.Net实现后,为加深印象将其改成Delphi代码。文中给出了基类、继承类、简单工厂类的定义及各函数实现部分,最后指出运行还需在interface部分加uses Sysutils。

昨天下午,看完 guoyan19811021 的设计模式之简单工厂模式(Simple Factory Pattern)(参见http://www.youkuaiyun.com/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操作的部分函数用到了它。

这样就完成了。

如有什么错误,请与联系

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值