我想写一个TCheckBox
and TRadioButton
后代有3个相同的方法。
TMyCheckBox = class(TCheckBox)
procedure DoSomething1;
procedure DoSomething2;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
end;
TMyRadioButton = class(TRadioButton)
procedure DoSomething1;
procedure DoSomething2;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
end;
// the following procedures are common for both classes, so in fact
// TMyCheckBox.DoSomething1 do the same as TMyRadioButton.DoSomething1
procedure DoSomething1;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;
procedure DoSomething2;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;
我怎样才能做到这一点?
定义一个接口说IDoSomething
与三个方法签名。
然后将您的类声明更改为
TMyCheckBox = class(TCheckBox, IDoSomething)
然后实施。
如果实现很常见或非常接近。
然后定义一个辅助类TDoSomething
然后委派工作。
e.g.
Procedure TMyCheckBox.DoSomething1; // implements IDoSomething1
Begin
TDoSomething.DoSomething1(Self); // given class method will suffice.
End;
delphi中的类方法,相当于其他语言中的静态方法。
Type
TDoSomethingHelper = Class(TObject)
Public
Class Procedure DoSomething1(aComponent : TComponent);
End;
...
implementation
Class Procedure TDoSomethingHelper.DoSomething1(aComponent : TComponent);
Begin
aComponent.Tag = 27;
End;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)