DesignPatterns. Composite

Для иерархических структур

client

program Composite;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  uComposer in 'uComposer.pas';

var
  l: TLetter;
  s: TSentence;

begin
  try
    l := TLetter.Create('!');
    s := TSentence.Create();
    try
      s.Sentence.Add(TLetter.Create('h'));
      s.Sentence.Add(TLetter.Create('e'));
      s.Sentence.Add(TLetter.Create('l'));
      s.Sentence.Add(TLetter.Create('l'));
      s.Sentence.Add(TLetter.Create('o'));

      s.Sentence.Add(TLetter.Create(' '));

      s.Sentence.Add(TLetter.Create('w'));
      s.Sentence.Add(TLetter.Create('o'));
      s.Sentence.Add(TLetter.Create('r'));
      s.Sentence.Add(TLetter.Create('l'));
      s.Sentence.Add(TLetter.Create('d'));

      s.Draw();
      l.Draw();

      Readln;
    finally
      l.Free();
      s.Free();
    end;

  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

uComposite

unit uComposer;

interface

uses
  System.SysUtils, System.Generics.Collections;

type
  // Component
  TAbstractLetter = class
    procedure Draw(); virtual; abstract;
  end;

  // Leaf
  TLetter = class(TAbstractLetter)
  private
    FLetter: string;
  public
    constructor Create(aLetter: char);
    procedure Draw(); override;
  end;

  // Composite
  TSentence = class(TLetter)
  private
    FSentence: TObjectList<TLetter>;
  public
    property Sentence: TObjectList<TLetter> read FSentence write FSentence;
    procedure Draw(); override;
  end;

implementation

{ TLetter }
constructor TLetter.Create(aLetter: char);
begin
  FLetter := aLetter;
end;

procedure TLetter.Draw;
begin
  WriteLn(FLetter);
end;

{ TSentence }
procedure TSentence.Draw;
var
  i: integer;
begin
  for i := 0 to FSentence.Count - 1 do
    FSentence[i].Draw();
end;

end.
This entry was posted in Без рубрики. Bookmark the permalink.