🤖📘🍻 Hooray! After 3 years of work, we've finally released a new ebook on design patterns! Check it out »

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)
  public
    constructor Create(AOwner: TComponent); override;
  end;

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

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

Code examples

More info, diagrams and examples of the Factory Method design pattern you can find on our new resource Refactoring.Guru.