Design Patterns Tutorial by Ivan Idris.
Introduction
Design patterns represent common software problems and the solutions to those problems in a
formal manner. They were inspired by a book written by architect Christopher Alexander.
Patterns were introduced in the software world by another book: "Design Patterns: Elements of
Reusable Object-Oriented Software", by Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides. These people were nicknamed the "Gang of Four" for some mysterious reason. The
Gang of Four describes 23 design patterns. With patterns you don't have to reinvent the wheel and
get proven solutions for frequently encountered problems. Many books and articles have been
written on this subject. This means that design patterns are becoming common knowledge, which
leads to better communication. To summarize design patterns save time, energy while making
your life easier.
Singleton
The singleton pattern deals with situations where only one instance of a class must be created.
Take the case of a system administrator or superuser. This person has the right to do everything in
a computer system. In addition we will also have classes representing normal users. Therefore we
must ensure that these classes have no access to the super user constructor. The solution to this
problem in C++ and Java is to declare the superuser constructor private. The superuser class itself
has a private static attribute sysadmin, which is initialised using the class constructor. Now we get
an instance of the super user class with a public static method that returns sysadmin. Here is the
class diagram:
Figure - Singleton Class Diagram
Factory Method
The Factory Method pattern deals with situations where at runtime one of several similar classes
must be created. Visualise this as a factory that produces objects. In a toy factory for instance we
have the abstract concept of toy. Every time we get a request for a new toy a decision must be
made - what kind of a toy to manufacture. Similarly to the Singleton pattern the Factory Method
pattern utilises a public static accessor method. In our example the abstract Toyfactory class will
have a getInstance() method, which is inherited by its non abstract subclasses.
Figure - Factory Method Class Diagram
Adapter
Sometimes you will have two classes that can in principle work well together, but they can't
interface with each other for some reason. This kind of problem occurs when travelling abroad
and you carry an electric shaver with you. Although it will work perfectly when you are at home.
There can be problems in a foreign country, because of a different standard voltage. The solution
is to use an adapter. Let's turn our attention back to the software domain. Here we will have an
interface which defines new methods for example getElectricity2. An adapter class will wrap
around the Shaver class. The adapter class will implement the interface with the new method.
Figure - Adapter Class Diagram
|