четверг, 26 февраля 2015 г.

Containers 3. Generics and without Generics...

Original in Russian: http://18delphi.blogspot.ru/2013/03/generic-generic.html

About containers. Table of contents

Akzhan Abdulin has already written it once... I am shaping... I have been using it for already 8 years...

Patterns in Delphi 7:

TList = class(Parent)
 Add(a: ItemType);
 Insert(i: Integer; a: ItemType);
 Sort();
end;

..

 TList.impl
 TList.Sort()
..
 CompareItems(a, b) : Integer;

..
 Parent = TObject;
 ItemType = integer;

{$include TList.intf}

TIntList = class(TList)
..

CompareItems(a, b : Integer) : Integer;
begin
 Result := a - b;
end;

{$Include TList.impl} 

-------------------------------------------------------------------
Example:

------------------------------------------------------------------------------------------------
IN TOTAL:

stack.imp.pas:

{$IfNDef Stack_imp}
 
{$Define Stack_imp}
 ItemsHolder = array of _ItemType_;
 
 _Stack_ = {mixin} class(TObject)
 private
 // private fields
   f_Items : ItemsHolder;
 public
 // public methods
   procedure Push(const anItem: _ItemType_);
   function Pop: _ItemType_;
 end;//_Stack_
 
{$Else Stack_imp}
 
// start class _Stack_
 
procedure _Stack_.Push(const anItem: _ItemType_);
var
 l_L : Integer;
begin
 l_L :=  Length(f_Items);
 SetLength(f_Items, l_L + 1);
 f_Items[l_L] := anItem;
end;//_Stack_.Push
 
function _Stack_.Pop: _ItemType_;
var
 l_L : Integer;
begin
 l_L :=  Length(f_Items) - 1;
 Result := f_Items[l_L];
 SetLength(f_Items, l_L);
end;//_Stack_.Pop
 
{$EndIf Stack_imp}

----------------------------------------------------------------------------------------------
IntStack.pas:

unit IntStack;
 
interface
 
type
 _ItemType_ = Integer;
 {$Include Stack.imp.pas}
 TIntStack = class(_Stack_)
 end;//TIntStack
 
implementation
 
{$Include Stack.imp.pas}
 
end.

----------------------------------------------------------------------------------------------
StringStack.pas:

unit StringStack;
 
interface
 
type
 _ItemType_ = AnsiString;
 {$Include Stack.imp.pas}
 TStringStack = class(_Stack_)
 end;//TStringStack
 
implementation
 
{$Include Stack.imp.pas}
 
end.

!!!! It is clear that DYNAMIC ARRAY is used here as an example. It is clear that we could have introduced PItemType = ^_ItemType_ and could have operated with pointers and GetMem. But it would have complicated the example.
It is also clear that there is no control of boundary conditions.

Try it. May be, you will like it.

And about the true generic's you can read here - http://keeper89.blogspot.ru/2011/07/delphi.html

One of my realizations of this idea is described here - http://18delphi.blogspot.com/2013/07/2_18.html



Комментариев нет:

Отправить комментарий