Tuesday, 29 October 2013

Delphi MVC


Main project file:
var
  Model: TModel;
  Controller: TController;
begin
  Application.Initialize;
  Application.CreateForm(TMainForm, MainForm);

  Model      := TModel.Create;
  Controller := TController.Create(Model, MainForm);

  Application.Run;

  Controller.Free;
  Model.Free;
end.
Model:
TModel = class(TSubject)
private
  FData: TStrings;
public
  constructor Create;
  destructor Destroy(); override;
  procedure AddLine(AText: string);
  property Data: TStrings read FData; // Do not write to this directly, since it doesn't call notify!
end;
Controller:
TController = class(TObserver)
private
  FModel: TModel;
  FView:  TMainForm;
public
  constructor Create(const AModel: TModel; AView: TMainForm);
  destructor Destroy(); override;
  procedure ButtonClick(Sender: TObject);
  procedure Refresh(ASubject: TSubject); override;
end;
The main form is working as the View, i have removed all code from it.
The controller registers itself as an observer and does all the logic:
constructor TController.Create(const AModel: TModel; AView: TMainForm);
begin
  inherited Create();
  FModel := AModel;
  FView  := AView;
  FModel.Register(Self);
  FView.Button1.OnClick := ButtonClick;
  FView.Button2.OnClick := ButtonClick;
  FView.Button3.OnClick := ButtonClick;
end;

destructor TController.Destroy;
begin
  FModel.UnRegister(Self);
  FView.Button1.OnClick := nil;
  FView.Button2.OnClick := nil;
  FView.Button3.OnClick := nil;
  inherited;
end;

procedure TController.Refresh(ASubject: TSubject);
begin
  FView.ListBox1.Items.BeginUpdate;
  try
    FView.ListBox1.Items.Assign(FModel.Data);
  finally
    FView.ListBox1.Items.EndUpdate;
  end;
end;

procedure TController.ButtonClick(Sender: TObject);
begin
  if Sender = FView.Button1 then begin
    FModel.AddLine('Hello');
  end else
  if Sender = FView.Button2 then begin
    FModel.AddLine('Hello World!');
  end else
  if Sender = FView.Button3 then begin
    FModel.AddLine(DateToStr(Now));
  end
end;
I cheated a little bit with the View <-> Controller relationship, but you should get the general idea :).
  • The Controller has references to both View and Model.
  • The View knows nothing about the Model.
  • The Model knows nothing aboug the View.
PS: A diagram for the MVC pattern (the dotted lines represent Observer/Subject relationships):
MVC diagram

No comments:

Post a Comment

Install Fortesreport community Delphi 7 dan RX Berlin

Download  Pertama2 kita harus punya file installernya terlebih dahulu, download  https://github.com/fortesinformatica/fortesrepo...