将数据从一个类迁移到另一个类

时间:2014-05-28 08:24:38

标签: delphi

取决于数据流(数据本身)我从一个非常简单的数据类型" AboutMe"开始,稍后取决于数据本身或我想继续使用此数据的工作流程在一个名为" AboutMe_more"的课程中。在我的程序中,此过程可能会发生1到3次。

AboutMe= class
      Name : String
      end;

AboutMe_more  = class(AboutMe)
       gender : String;
       Birth  : TDate;

Aboutme_complete = class (AboutMe_more)
       adresss : String;
       salery : Real;
       .....
       end;

从完整的类开始在我的情况下不是一个好主意,因为可能有一个不同的开关到其他所需的类,如

Aboutme_complete_option = class (AboutMe_more)
      company : string;
      city  : String;
      kids : String;
       .....
       end;

问:

a)将数据从一个类传输到派生类的最佳方法是什么,不需要将数据传输到父类。 b)良好的编程风格或者对数据运动的需求是否表明阶级结构/设计较差?

1 个答案:

答案 0 :(得分:-1)

看起来您正在尝试使用对象建模数据库。

  

b)良好的编程风格或对数据运动的需求是否表明一个糟糕的阶级结构/设计?

这里的问题(正如@jpfollenius所提到的)是你最终会得到一个非常深层次的对象层次结构。

  

a)将数据从一个类传输到派生类[...]的最佳方法是什么?

我不了解最佳方式,但在Delphi中,通常使用重载Assign将数据从一个对象传输到另一个对象。

TMyObject = class(TPersistent)
  procedure Assign(Source: TPersistent); overload;
  ....

implementation

procedure TMyObject.Assign(Source: TPersistent);
 begin
  inherited Assign(Source);
  if (Source is TMyObject) then begin
    Self.Field1:= Source.Field1;
    Self.Field2:= Source.Field2;
  end;
end;

更明智的做法
继承只是解决此问题的一种方法。 更合适的方法是使用封装。

这里有一个对象和一个接口,用于保存数据和容器对象,使您可以访问该数据 Delphi有一个非常好的机制,因为它允许您将接口的实现委托给包含的对象。

使用带有接口和容器对象的2个数据对象的示例。

type
IData1 = interface
['{3F996D68-1FD0-4490-AE60-8F735A9DFFE8}']  //Use ctrl+alt+g to generate a number
    function GetData1: integer;
    procedure SetData1(value: integer);
    property Data1: integer read GetData1 write SetData1;
  end;

IData2 = interface
['{3F996D68-1FD0-4490-AE60-8F735A9DFFE9}']
    function GetData2: integer;
    procedure SetData2(value: integer);
    property Data2: integer read GetData2 write SetData2;
  end;

TData1 = class(TInterfacedObject, IData1);
private
  FData1: integer;
protected 
  function GetData1: integer;
  procedure SetData1(value: integer);
public
  property Data: integer read GetData1 write SetData1;
end;

TData2 = class(TInterfacedObject, IData2);
{see TData1 above}

TContainer = class(TInterfacedObject, IData1, IData2)
  private
    FData1: TData1; 
    FData2: TData2;
  public
    constructor Create();
    property Data1: TData1 read FData1 implements IData1; //delegates implementation to object FData.
    property Data2: TData2 read FData2 implements IData2; 
  end; 

从这个问题复制:https://stackoverflow.com/questions/6063274/hidden-features-in-the-delphi-language(现在遗憾地删除了)。

相关问题