delphi泛型模板编程

delphi泛型模板编程

泛型模板编程的关键:泛型作用体现在模板,体现在虚实之间相互转换。以虚御实,以实立虚,虚中有实,实中有虚,虚事实做,实事虚做。框架、流程。。无不如此,编程之道。

unit TxInfo;

interface

uses
  System.Types,
  System.Classes,
  System.SysUtils,
  Generics.Collections;

type
  TPeople = record
    Name: string;
    Age: string;
  end;

type
  TTxInfo<T> = class
  public
    PeopleList: TList<T>;
  public
    constructor Create;
    destructor Destroy; override;
  private
    function ProcessInfo(aAPeopleStr: string): T; virtual; abstract;
  public
    procedure GetInfo(AStr: string); overload;
  end;

type
  TMyNetInfo<T> = class(TTxInfo<T>)//泛型类可以继承
  public
    function ProcessInfo(APeopleStr: string): T; override;
  end;

implementation

{ TTxHttp }
constructor TTxInfo<T>.Create;
begin
  inherited Create();
  PeopleList := TList<T>.Create;
end;

destructor TTxInfo<T>.Destroy;
begin
  PeopleList.Free;
  inherited Destroy;
end;

procedure TTxInfo<T>.GetInfo(AStr: string);
var
  m_Info: T;
begin
  PeopleList.Clear;
  m_Info := ProcessInfo(AStr);
  PeopleList.Add(m_Info);
end;

{ TMyNetInfo<TFilmInfoT> }
function TMyNetInfo<T>.ProcessInfo(APeopleStr: string): T;
begin
  var pepole: TPeople;
  pepole.Name:= APeopleStr;
  Result:=T(Pointer(@pepole)^);//实转虚
end;

end.

 

procedure TPool<T>.Unlock(Value: T);
begin
  FCS.Enter;
  try
    if TComponent(Addr(Value)).Tag = DynCreate then //虚转实
      Value.free
    else
    begin
      FList.Add(Value);
    end;
  finally
    FCS.Leave;
  end;
end;

  

 泛型模板编程

//cxg 2023-10-3

unit pool;

interface

uses
  System.Generics.Collections, Classes, SyncObjs, SysUtils, DateUtils;

const
  DynCreate = 5;

type
  TPool<T: class> = class
  private
    FCS: TCriticalSection;
    FList: TList<T>;
    FPoolSize: Integer;
  public
    constructor Create; virtual;
    destructor Destroy; override;
  protected
    procedure Init; virtual;
    function NewObj(owner: TComponent = nil): T; virtual; abstract;
  public
    function Lock: T;
    procedure Unlock(Value: T);
  end;

implementation

{ TPool<T> }

constructor TPool<T>.Create;
begin
  inherited;
  FList := TList<T>.create;
  FCS := TCriticalSection.Create;
end;

destructor TPool<T>.Destroy;
begin
  FList.Clear;
  FreeAndNil(FList);
  FreeAndNil(FCS);
  inherited;
end;

procedure TPool<T>.Init;
begin
  while FList.Count < Self.FPoolSize do
    FList.Add(NewObj(nil));
end;

function TPool<T>.Lock: T;
begin
  FCS.Enter;
  try
    if FList.Count > 0 then
    begin
      Result := FList.Last;
      FList.Delete(FList.Count - 1);
    end
    else
    begin
      Result := NewObj;
      TComponent(TypeInfo(Result)).Tag := DynCreate;
    end;
  finally
    FCS.Leave;
  end;
end;

procedure TPool<T>.Unlock(Value: T);
begin
  FCS.Enter;
  try
    if TComponent(TypeInfo(Value)).Tag = DynCreate then
      Value.free
    else
    begin
      FList.Add(Value);
    end;
  finally
    FCS.Leave;
  end;
end;

end.

  

  

  

posted @ 2023-10-03 11:09  delphi中间件  阅读(225)  评论(0编辑  收藏  举报