在Delphi中避免代码重复

时间:2011-05-27 17:32:50

标签: delphi components dry code-duplication

我有两个组件A和B.组件B派生自组件A,并与它共享大多数属性和过程。现在我有一个冗长的程序:

procedure DoSomething;
begin
  Form1.Caption := Component_A.Caption;
  // hundreds of additional lines of code calling component A
end;

根据组件B是否处于活动状态,我想重用上述过程并将Component_A部分替换为组件B的名称。它应该如下所示:

procedure DoSomething;
var
  C: TheComponentThatIsActive;
begin
  if Component_A.Active then
    C := Component_A;
  if Component_B.Active then
    C := Component_B;
  Form1.Caption := C.Caption;
end;

我怎样才能在Delphi2007中做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:4)

TheComponentThatIsActive应与ComponentATComponentA)的类型相同。

现在,如果你遇到一个绊脚石,其中一些属性/方法只属于ComponentB,那么检查并对其进行类型转换。

procedure DoSomething;
var
    C: TComponentA;

begin
    if Component_A.Active then
        C := Component_A
    else if Component_B.Active then
        C := Component_B
    else
        raise EShouldNotReachHere.Create();

    Form1.Caption := C.Caption;

    if C=Component_B then
        Component_B.B_Only_Method;
end;

答案 1 :(得分:2)

您可以将ComponentA或ComponentA作为参数传递给Do Something。

ComponentA = class
public 
 procedure Fuu();
 procedure Aqq();
end;

ComponentB = class(ComponentA)
public 
 procedure Blee();
end;

implementation

procedure DoSomething(context:ComponentA);
begin
  context.Fuu();
  context.Aqq();
end;

procedure TForm1.Button1Click(Sender: TObject);
var cA:ComponentA;
    cB:ComponentB;
begin
  cA:= ComponentA.Create();
  cB:= ComponentB.Create();

  DoSomething(cA);
  DoSomething(cB);

  cA.Free;
  cB.Free;
end;