Decorator Design Pattern in Delphi. Single decoration

Decorator (also referred as Wrapper) is classified by GoF as a structural pattern. Its purpose is to:

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”  

Both inheritance and the decorator pattern aim towards extending the functionality. This is what they have in common.

There are a couple of remarkable differences:
  • Inheritance extends the functionality at compilation time (statically). The decorator pattern extends the functionality at runtime (dynamically).
  • Inheritance extends the functionality of a whole class (all objects of the extended class get the extended functionality). The decorator pattern allows extending the functionality of a selected object (or group of objects) without affecting the remaining objects.  

You can think of the decorator pattern as a way to add make-up to an object or even as a way to attach accessories to that object. All this is done on the fly after the object itself has been created.

Let’s walk through a simple task to get the idea. This example might sound silly. I want it silly so that you can focus on the decorator implementation, avoiding any extra complexity.

Please, be aware that this design is somewhat unfinished, since we are only covering the case for a single decoration (just one functionality to be extended). In real life, we will need multiple decorators in order to add multiple responsibilities. As this is a controlled example (just for the purpose of this discussion), I am enforcing that only ONE responsibility is going to be extended. This means, we will have ONE decorator class. Because of that, I have made some simplifications to the design; so that you get a taste of the decorator pattern in its simplest expression.

Later on, in other post, we’ll see how to add multiple responsibilities (with multiple decorator classes). For that, we’ll need a more complex design to overcome the shortcomings of this initial example. For now, just get the idea...we'll come back later to the multiple decorations scenario.

If you get some time, take a look at the discussion in the comments section.

Subtask 1: Let’s create a TConsole class which purpose is to output a given text to the standard output. The code might be something like this:

interface
type
  TConsole = class
  public
    procedure Write(aText: string);
  end;

implementation

procedure TConsole.Write(aText: string);
begin
  Writeln(aText);
end;

Subtask 2: Let’s use the TConsole class to printout “Hello World!”. The following code snipped does it:

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end.

This is how the output looks like:

Hello World!

Subtask 3: Now, let’s decorate the object referenced by MyConsole (only that object, not the whole class). What I want is to upper case every text to be printed out. We need to define a decorator class TUpperCaseConsole for that purpose. See the code:

interface

uses
  SysUtils;

type
  TConsole = class
  public
    procedure Write(aText: string); virtual;
  end;


  //Decorator
  TUpperCaseConsole = class(TConsole)
  private
    FConsole: TConsole;
  public
    constructor Create(aConsole: TConsole);
    destructor Destroy; override;

    procedure Write(aText: string); override;
  end;

implementation

{ TConsole }

procedure TConsole.Write(aText: string);
begin
  Writeln(aText);
end;

{ TUpperCaseConsole }

constructor TUpperCaseConsole.Create(aConsole: TConsole);
begin
  inherited Create;
  FConsole:= aConsole;
end;

destructor TUpperCaseConsole.Destroy;
begin
  FConsole.Free;
  inherited;
end;

procedure TUpperCaseConsole.Write(aText: string);
begin
  aText:= UpperCase(aText);
 
FConsole.Write(aText);
end;

Notice in the code above that the decorator class (TUpperCaseConsole) inherits from the decorated class (TConsole). This makes both the decorated and the decorator objects to share the same public interface. Furthermore, the TUpperCaseConsole class Has-A field of the TConsole type. We’ll use this field to forward the printing functionality to the TConsole class, once we have applied the cosmetic (upper case transformation) to the text.

Subtask 4: Let’s now create some consuming code to decorate one TConsole object on the fly. Note how the TUpperCaseConsole constructor wraps (decorates) the object referenced by MyConsole.

var
  MyConsole: TConsole;
begin
  MyConsole:= TConsole.Create;
  MyConsole:= TUpperCaseConsole.Create(MyConsole);
  try
    MyConsole.Write('Hello World!');
  finally
    MyConsole.Free;
  end;
  Readln;
end.

This is how the output looks like after the decorator has been applied:

HELLO WORLD!  

In real life, you’ll have to judge whether the decorator pattern is the best alternative to be applied to solve a particular problem. Not always it the right way to go with. For more details get your hands on these classic books.

Anonymous Methods in Delphi

Under the scope of Delphi, an anonymous method is either a procedure or function that’s unattached to an identifier. In other words, anonymous methods don’t have names, which is why they are called “anonymous”.

Basically, you can assign a block of code (in the form of a procedure or function) directly to a variable.

I am going to give you a simplistic example. I am going to Keep it simple, Stupid! to avoid distracting you with any complexity.

This is the wording of the task: create a console application which prints “Hello world” and “Good bye” to the standard output. Constraint: use the Writeln function just once in the code.

To accomplish such reckless task in the old days (before the introduction of anonymous methods) you could do this:

program Project1;

{$APPTYPE CONSOLE}

procedure PrintString(aText: string);
begin
 Writeln(aText);
end;

begin
  PrintString('Hello world');
  PrintString('Good bye');
  Readln;
end.

How to do the same with anonymous methods? Take a look at the following code:

program Project1;

{$APPTYPE CONSOLE}

type
  TMyAnonymousProcedureType = reference to procedure(aText: string);

var
  A: TMyAnonymousProcedureType;

begin
  A:= procedure(aText: string) //No semicolon here
                begin
                  Writeln(aText);
                end;
  A('Hello world');
  A('Good bye');
  Readln;
end.

As you can see in the example above, we have assigned code directly to the variable A. Then, we called A with parameters, and VoilĂ !: we have accomplished our reckless task with anonymous methods as well.

Pay attention to this:  if you are tented to declare variable A like this:

var
  A: reference to procedure(aText: string);

Don’t! That shortcut doesn’t work. You’ll get a compilation error…like this:

Undeclared identifier: ‘reference’

So, you do need to declare:

type 
   TMyAnonymousProcedureType = reference to procedure(aText: string);


Only later you can define the type of variable A.

You might be asking by now: why to bother with all this? What's the benefit? Well, in the previous example there’s little or none benefit present.

Generally speaking, anonymous methods are handy in the following cases:
  • You have been trying to name a local method for hours. You cannot think of a name for it. Well, think no more: use anonymous methods. Don’t put a tasteless name like Foo(), XXX(), Aux(), etc.
  • You create a function that is called just once(it’s just called from one spot).
  • You can use anonymous methods to provide elegant and simpler implementations. This is the case when combining generics types with anonymous methods for example. I should write about this shortly. Subscribe to my feed and stay tuned :-)
With this post I wanted to introduce anonymous methods to you. It’s OK if you don’t see the benefits clearly right now. You’ll get there :-)

Hide the utter "Create" constructor of TObject in Delphi

In Delphi, constructors can be inherited; this doesn’t happen in Java, C# and C++ for example. Furthermore, constructors in Delphi can have multiple and different names; usually they are called Create, but this is just a convention, since you can define a constructor with whatever name you choose.

In addition to all this, all classes in Delphi inherit ultimately from TObject, which contains a public parameterless constructor, named Create.

Due to the facts above, it‘s easy to understand that all classes in Delphi have a public Create parameterless constructor, that has been inherited from TObject.

I am not going to discuss here whether this is bad or good. What I want to show you is a way to hide the public Create parameterless constructor of TObject in case you need to do so.

Burn this out: you cannot hide any member (field, method, constructor, destructor) in Delphi by decreasing the level of visibility. If a member in a superclass is public, you cannot hide it in a child class by changing the visibility to protected or private. Once public you are always public. This means, you cannot hide the public Create parameterless constructor of TObject by lowering its visibility in an inheriting class.

So, how can we hide the Create constructor of TObject? Is there even a way for doing so? Yes, there is a way. We came to the solution in the LinkedIn’s Delphi Professionals group. I thought it would be worthy to share this with the rest of the Delphi community.

Basically, you can hide the public Create parameterless constructor of TObject with another public method having the same Create name. For example:

Class definition snipped:

TSomeClass = class(TObject)
public
//this constructor takes two parameters, and hides the TObject.Create()
constructor Create(aParameter1: string; aParameter2: Integer );
end;

Consuming code snipped:

var
  SomeObject: TSomeClass;
begin
  SomeObject:= TSomeClass.Create; //This does not compile!

  //This compiles. Uncomment and try...
  // SomeObject:= TSomeClass.Create('Hello People!', 12);

  try
    //TODO
  finally
    SomeObject.Free;
  end;
end;

See, in the code above the TObject.Create() has been hidden :-)

There is another consideration though: What happens if we overload the Create constructor?

TSomeClass = class(TObject)
public
  //this one takes two parameters, and hides the TObject.Create()
  constructor Create(aParameter1: string; aParameter2: Integer ); overload;
  constructor Create(aThisTakesAChar: Char); overload;
  constructor Create(aThisTakesAnInteger: Integer); overload;
end;

By overloading the Create constructor we have made the TObject.Create() visible again. If we want to keep it hidden, then we should avoid overloading. For that, you can simply use a different name for the new constructors being added. Something like this:

TSomeClass = class(TObject)
public
  //this one takes two parameters, and hides the TObject.Create()
  constructor Create(aParameter1: string; aParameter2: Integer );
  constructor Create2(aThisTakesAChar: Char);
  constructor Create3(aThisTakesAnInteger: Integer);
end;

Now the TObject.Create() constructor is hidden again.

Consuming code:

var
  SomeObject: TSomeClass;
begin
  SomeObject:= TSomeClass.Create; //This does not compile!

  //This compiles. Uncomment and try...
  // SomeObject:= TSomeClass.Create('Hello People!', 12);

  //This compiles. Uncomment and try...
  // SomeObject:= TSomeClass.Create1('H');

  //This compiles. Uncomment and try...
  // SomeObject:= TSomeClass.Create2(12);

  try
    //TODO
  finally
    SomeObject.Free;
  end;
end;

Why would someone want to hide the TObject.Create() anyway? It depends on the situation. I have found this very useful when implementing a singleton class in Delphi. For details refer to: Singleton class in Delphi.

As a conclusion, you can hide the TObject.Create() constructor by defining a new public method with the name Create in the inheriting class. You cannot hide TObject.Create() by lowering the visibility to protected, private, etc.

My contributions to the Delphi community at RosettaCode

RosettaCode is a wiki site that gathers a collection of programming tasks being resolved in as many programming languages as possible.

You can post solutions to a particular task using a particular language (Delphi, Java, C++, C#, Ruby, the list goes and goes).  All solutions to the same task are coded in the same page, allowing a fast knowledge transfer from one language to the other. Also, you can compare how suitable is a particular language for a particular task.

Furthermore, you can add programming languages to be considered for implementation and of course, you can suggest new tasks to be resolved.

There is very little about Delphi at RosettaCode. I encourage the Delphi community to fill the pending tasks for Delphi and suggest new tasks as well.

Delphi is very powerful, let’s share it with everybody.

These are my contributions so far:
Finally, I want to highlight that RosettaCode is about all programming languages. Resolving tasks in a single language is not enough. Don’t be shy, add the solutions in all the languages you can :-)

Setting up InfoLinks ads for your Website

InfoLinks is a way for monetizing your Web content through contextual advertisement. It is very popular these days; not as popular as AdSense yet, but it is coming close.

I do like the way they place the ads: the ads are made by converting phrases (or words) from your own website into advertising links. If the reader moves the mouse over those links, then an advertisement dialog pops-up. If the reader is interested, then he/she can click the ad for more information; if not, he/she just moves the mouse away from the link and continues reading normally.

What I like the most so far is that ads come naturally within the content. This is done pretty much automatically. You just need to put a script into your HTML template and the rest if taken care on the fly. Of course, you can also customize your InfoLinks ads.

To use InfoLinks you’ll need to register. They don’t ask much. Filling the registration information just takes 5 minutes or less.

After registering you’ll receive an email saying your Website (the one you filled in the registration process) is under review and that you should receive a confirmation of acceptance within 2 business days. Well, this took a little longer for me. InfoLinks accepted my website 9 days after I registered. I guess InfoLinks guys are too busy.

Right now you can see the InfoLinks ads showing up alongside with AdSense in this blog. Yes, InfoLinks and AdSense can coexist.

I believe InfoLinks is worthy to be tried. It doesn’t cost you much effort to set-up and all websites are welcome, no matter if they are highly trafficked or not. There are a few exceptions: they don’t want porn sites, etc. 

Many people are saying that InfoLinks beats AdSense in terms of how much revenue you can get from them. Now that I am running both of them together, I can see the numbers by myself.  I’ll write my findings about this in a month or two. Whatever the outcome, remember that InfoLinks and AdSense are complementary advertisement alternatives from which you can benefit.