delphi - 如何将 DRY 应用于涉及 Form 组件的接口(interface)实现?

标签 delphi interface delphi-xe2 dry

我有一个接口(interface)IComm声明一个例程 SetMonitorLogLevel() :

unit IFaceComm;
interface
type
  TMonitorLogLevel = (mllOnlyImportant, mllAll);

  IComm = Interface(IInterface)
    procedure SetMonitorLogLevel(LogLevel: TMonitorLogLevel);
  end;

end.

接口(interface)由2个Form实现,彼此相似,frmBarCommfrmFooComm ,看起来像这样:
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/

相关文章:

typescript - 为什么以下 TypeScript 程序不会抛出类型错误?

Delphi 7 应用程序和 Microsoft 安全要点

delphi - TRichEdit 支持 Unicode 吗?

c# - "Neighbor function"使用 A* 算法优化解决 8-Puzzle

c++ - 为什么 std::map::insert 不能采用键和值而不是 std::pair?

json - 将 JSON 解析为 TListBox

delphi - TEmbeddedWB 中的 Youtube 视频不再工作?

delphi - 有没有办法在 Delphi 中找到未使用的事件处理程序?

delphi - FireMonkey XE5 - Livebounds Grid - 单元格文本对齐

c++ - C++ 中带有纯虚方法的抽象模板类