A Simple start with MVP in Delphi for Win32, Part 2
Delphi 2010, Delphi Dependency Injection, Design Patterns, MVC, MVP, Uncategorized 4 Comments »Some month ago I wrote a simple article about an MVP variant called PassiveView.
That example was very simple. Now I’ll present a more “advanced” version of that example.
The main problem with first example was the following method:
-
procedure TfrmCalculatorView.FormCreate(Sender: TObject);
-
begin
-
//Link controls with related interface
-
IFirstOperand := TGUIEdit.Create(EditFirstOp);
-
ISecondOperand := TGUIEdit.Create(EditSecondOp);
-
ICalcResult := TGUIEdit.Create(EditResult);
-
IOperators := TGUISelectableList.Create(ComboOperators);
-
IError := TGUIEdit.Create(EditError);
-
-
//link view and presenter
-
FPresenter := TCalculatorPresenter.Create(Self); //<<– THIS IS THE BAD LINE
-
end;
The “BAD” line links the View with the Presenter but it’s in the view code, so this is meaning that View KNOWS the presenter… and this is not a good thing becouse the view is not so “passive”.
In a more advanced (and complex) version the View should be completely ignorant about the class that implement the presenter and the service.
In the main dpr file now the code now looks like the following.
-
var
-
MainPresenter: ICalculatorPresenter;
-
CalculatorView: TForm;
-
begin
-
Application.Initialize;
-
Application.MainFormOnTaskbar := True;
-
//SETUP THE MAIN APPLICATION FORM FOR VCL PURPOSE
-
Application.CreateForm(TfrmCalculatorView, CalculatorView);
-
//SETUP ALL THE LINKS BETWEEN THE MVP TRIAD
-
MainPresenter := TCalculatorPresenter.Create(CalculatorView as ICalculatorView, TCalculatorService.Create);
-
//LETS START!
-
Application.Run;
-
end.
Now the presenter take care about all links between the MVP triad.
-
constructor TCalculatorPresenter.Create(CalculatorView: ICalculatorView;
-
CalculatorService: ICalculatorService);
-
begin
-
inherited Create;
-
FCalculatorService := CalculatorService;
-
FCalculatorView := CalculatorView;
-
FCalculatorView.SetPresenter(self);
-
InitView; //does the links
-
end;
There is another addition to the previous example. Now there is only one constructor in the presenter, and using dependency injection take 2 interface for the view and the service.
-
constructor Create(CalculatorView: ICalculatorView; CalculatorService: ICalculatorService);
Another plus is the possibility to open the same form a number of times without change the code for create it.
This is the GUI for this simple application.
As bonus, unit tests and mock object arent changed.
As usual the source code is here.






Recent Comments