我有一个接口(interface)IComm
声明一个例程 SetMonitorLogLevel()
:
unit IFaceComm;
interface
type
TMonitorLogLevel = (mllOnlyImportant, mllAll);
IComm = Interface(IInterface)
procedure SetMonitorLogLevel(LogLevel: TMonitorLogLevel);
end;
end.
接口(interface)由2个Form实现,彼此相似,
frmBarComm
和 frmFooComm
,看起来像这样:TfrmBarComm = class(TForm, IFaceComm.IComm)
cboDebugLevel: TComboBox;
private
procedure SetMonitorLogLevel(LogLevel: IFaceComm.TMonitorLogLevel);
end;
请注意,这 2 个 Forms 有很多共同的组件,例如
cboDebugLevel
, 但也可以有其他没有的组件。两种形式都实现了
IComm.SetMonitorLogLevel()
在 完全一样方式:procedure TfrmBarComm.SetMonitorLogLevel(LogLevel: IFaceComm.TMonitorLogLevel);
begin
case LogLevel of
IFaceComm.TMonitorLogLevel.mllOnlyImportant:
Self.cboDebugLevel.ItemIndex := 0;
IFaceComm.TMonitorLogLevel.mllAll:
Self.cboDebugLevel.ItemIndex := 1;
end;
end;
如何避免违反不要重复自己 (DRY) 原则?我经常遇到这个问题,当复制粘贴的例程比我上面显示的简单示例大得多时,它特别难看。
最佳答案
处理这个问题的常用方法是创建另一个实现接口(interface)的类。它可能看起来像这样:
type
TComboBoxCommImplementor = class(TInterfacedObject, IFaceComm.IComm)
private
FDebugLevel: TComboBox;
public
constructor Create(DebugLevel: TComboBox);
procedure SetMonitorLogLevel(LogLevel: TMonitorLogLevel);
end;
constructor TComboBoxCommImplementor.Create(DebugLevel: TComboBox);
begin
inherited Create;
FDebugLevel := DebugLevel;
end;
procedure TComboBoxCommImplementor.SetMonitorLogLevel(
LogLevel: IFaceComm.TMonitorLogLevel);
begin
case LogLevel of
IFaceComm.TMonitorLogLevel.mllOnlyImportant:
FDebugLevel.ItemIndex := 0;
IFaceComm.TMonitorLogLevel.mllAll:
FDebugLevel.ItemIndex := 1;
end;
end;
然后在您的表单中使用委托(delegate)实现接口(interface):
type
TfrmBarComm = class(TForm, IFaceComm.IComm)
cboDebugLevel: TComboBox;
private
FComm: IFaceComm.IComm;
property Comm: IFaceComm.IComm read FComm implements IFaceComm.IComm
public
constructor Create(AOwner: TComponent); override;
end;
constructor TfrmBarComm.Create(AOwner: TComponent);
begin
inherited;
FComm := TComboBoxCommImplementor.Create(cboDebugLevel);
end;
关于delphi - 如何将 DRY 应用于涉及 Form 组件的接口(interface)实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32272106/