Модераторы: Poseidon, Snowy, bems, MetalFan
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Оптимизация классов 
V
    Опции темы
JS2
Дата 24.4.2009, 14:58 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 55
Регистрация: 25.3.2009

Репутация: нет
Всего: нет



Помогите с оптимизацие классов, убрать дублирующийся код: есть два класса, по сути списки определенных record'ов. Вот код: 

Код

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Contnrs;

type
  TRecA = record
    IdA: Integer;
  end;
  PRecA = ^TRecA;

  TListA = class
  private
    FList: array of TRecA;
    FCapacity: Integer;
    FCount: Integer;
    function GetItems(Index: Integer): TRecA;
  public
    constructor Create(ACapacity: Integer = 100);
    destructor Destroy; override;
    function Add(AIdA: Integer): Integer;
    function Count: Integer;
    property Items[Index: Integer]: TRecA read GetItems; default;
  end;

  TRecB = record
    ParentA: Integer;
    Name: string[255];
  end;
  PRecB = ^TRecB;

  TListB = class
  private
    FList: array of TRecB;
    FCapacity: Integer;
    FCount: Integer;
    function GetItems(Index: Integer): TRecB;
  public
    constructor Create(ACapacity: Integer = 100);
    destructor Destroy; override;
    function Add(AParentA: Integer; AName: string): Integer;
    function Count: Integer;
    property Items[Index: Integer]: TRecB read GetItems; default;
  end;

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    FlistA: TlistA;
    FlistB: TlistB;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TlistA }

function TListA.Add(AIdA: Integer): Integer;
begin
  Inc(FCount);
  if FCount > FCapacity then begin
    Inc(FCapacity, FCapacity);
    SetLength(FList, FCapacity);
  end;
  Result := FCount - 1;
  FList[Result].IdA := AIdA;
end;

function TListA.Count: Integer;
begin
  Result := FCount;
end;

constructor TListA.Create(ACapacity: Integer);
begin
  Assert(ACapacity > 0);
  FCount := 0;
  FCapacity := ACapacity;
  SetLength(FList, FCapacity);
end;

destructor TListA.Destroy;
begin
  Finalize(FList);
  inherited Destroy;
end;

function TListA.GetItems(Index: Integer): TRecA;
begin
  Assert(Index < FCount);
  Result := FList[Index];
end;

{ TListB }

function TListB.Add(AParentA: Integer; AName: string): Integer;
begin
  Inc(FCount);
  if FCount > FCapacity then begin
    Inc(FCapacity, FCapacity);
    SetLength(FList, FCapacity);
  end;
  Result := FCount - 1;
  FList[Result].ParentA := AParentA;
  Flist[Result].Name := AName;
end;

function TListB.Count: Integer;
begin
  Result := FCount;
end;

constructor TListB.Create(ACapacity: Integer);
begin
  Assert(ACapacity > 0);
  FCount := 0;
  FCapacity := ACapacity;
  SetLength(FList, FCapacity);
end;

destructor TListB.Destroy;
begin
  Finalize(FList);
  inherited Destroy;
end;

function TListB.GetItems(Index: Integer): TRecB;
begin
  Assert(Index < FCount);
  Result := FList[Index];
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  FlistA := TListA.Create;
  FlistA.Add(1);
  FlistA.Add(2);

  FlistB := TlistB.Create;
  FlistB.Add(1, 'I');
  FlistB.Add(1, 'P');
  FlistB.Add(2, 'S');

  for i := 0 to FlistA.FCount - 1 do
    ShowMessageFmt('%d', [FlistA.Items[i].IdA]);
  for i := 0 to FlistB.FCount - 1 do
    ShowMessageFmt('%d; %s', [FlistB.Items[i].ParentA,
      FlistB.Items[i].Name]);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FlistA.Free;
  FlistB.Free;
end;

end.


PM MAIL   Вверх
Bose
Дата 25.4.2009, 01:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник Клуба
Сообщений: 1458
Регистрация: 5.3.2005
Где: Riga, Latvia

Репутация: 23
Всего: 51



Generics?
PM MAIL WWW Skype   Вверх
kami
Дата 25.4.2009, 11:13 (ссылка) |    (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Завсегдатай
Сообщений: 1806
Регистрация: 25.8.2007
Где: Санкт-Петербург

Репутация: 23
Всего: 72



Сделать им одного предка, убрав в него общие процедуры.
PM MAIL WWW   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Delphi: Общие вопросы"
SnowyMetalFan
bemsPoseidon
Rrader

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по Дельфи обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь
  • 90% ответов на свои вопросы можно найти в DRKB (Delphi Russian Knowledge Base) - крупнейшем в рунете сборнике материалов по Дельфи


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Snowy, MetalFan, bems, Poseidon, Rrader.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Delphi: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0836 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.