Factory Method Design Pattern in Delphi

Applications in Delphi

This pattern is useful when you want to encapsulate the construction of a class and isolate knowledge of the concrete class from the client application through an abstract interface.

One example of this might arise if you had an object oriented business application potentially interfacing to multiple target DBMS. The client application only wants to know about the business classes, not about their implementation-specific storage and retrieval.

Implementation Example

In the Abstract Factory example, each of the virtual widget constructor functions is a Factory Method. In their implementation we define a specific widget class to return.

TRedSpeedButton = class(TSpeedButton)
    constructor Create(AOwner: TComponent); override;

constructor TRedSpeedButton.Create(AOwner: TComponent);
  inherited Create(AOwner);
  Font.Color := clRed;

function TORedFactory.CreateSpeedButton(AOwner: TComponent): TSpeedButton;
  Result := TRedSpeedButton.Create(AOwner);

Code examples