Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi 7 - trying to understand the MVC pattern [closed]

I am trying to understand the MVC pattern and this is what I came up with. If you could be so kind and tell me if I did it correctly, suggest some improvments, or diss me for failing completely, I'd be more than happy!

Here's a link to the project (Delphi 7): http://www.sendspace.com/file/ynpgre

like image 744
Pateman Avatar asked Jul 29 '11 12:07

Pateman


1 Answers

I have rewritten your project to use 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

like image 129
Jens Mühlenhoff Avatar answered Sep 21 '22 19:09

Jens Mühlenhoff