Archive | Design Patterns RSS for this section

Decorator

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

Design Patterns: Elements of Reusable Object-Oriented Software

Imagine the time before fancy and automatic GUIs, and the case of a simple textview. Sometimes, we enter more information in it than it can show. The behavior which we are accustomed to in these cases is that suddenly a scrollbar will appear out of nowhere, and magic! we can scroll down to see the rest of the text entered. But do we always need that scrollbar? If we’d create a subclass for textview with the name TextViewWithScrollBar, and use it anyway, would it make sense?

No it wouldn’t, we’d only need those bars whenever we exceed the space given us within the textview. And we cannot see that fore. So what is the solution?

From the title, you can guess easily that it’s nothing else but the Decorator pattern. Notice the following: “Attach additional responsibilities to an object dynamically.”. Not a class, but an instance of a given class, the object. This is the key phrase here. But how can we achieve such behavior. The answer is simple, we need four players here:

  • Component: a very brief and lightweight interface for your objects that can have dynamic responsibilities (such as render a scrollbar).
  • ConcreteComponent: the object itself which implements Component.
  • Decorator: implements Component, and maintains a reference to a ConcreteComponent.
  • ConcreteDecotator: adds the dynamic responsibilities to ConcreteComponent, implements Decorator.

Now a code example for the above:

Read More…

Composite

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”

Design Patterns: Elements of Reusable Object-Oriented Software

A Composite is something really simple and straightforward, with countless examples in the computing world (at least I found quite many examples for it). You can easily imagine it as a tree structure: a node can be a composite, or a leaf. Composites can contain further composites and/or leaves, and so forth.

The big advantage in this pattern is that it lets you treat primitive and container objects in the same manner, thus simplifying your code. Now let’s understand the key players here:

  • Component: defines the interface for the objects of the composition, their default behavior, the method to get or set the child components.
  • Leaf: primitives of the composition which haven’t got child objects.
  • Composite: components that have child objects, defining their own child-management methods.
  • Client: works with composition through the component interface.

An example is the View object in the Cocoa Touch Framework (to get a bit further from the .NET Framework). Each View can have further Views which can be accessed through the parent View. But here’s a .NET sample:

Read More…

Bridge

“Decouple an abstraction from its implementation so that the two can vary independently.”

Design Patterns: Elements of Reusable Object-Oriented Software

The Bridge pattern is a bit mysterious for me, I’m trying to find a concrete implementation of it in the .NET Framework, but it is a bit hard task. The main point in bridge is to decouple the implementation from its abstraction, and let them evolve separately. We have four key players here:

  • Abstraction: is the interface our client is aware of. It also maintains a reference on the implementation (something moved into the RefinedAbstraction commonly).
  • RefinedAbstraction: implements Abstraction, and extends its functionality (in all examples, the reference to Implementor was moved here).
  • Implementor: defines the functionality of abstraction, and the methods to call.
  • ConcreteImplementor: extends implementor.

Now let’s see a real example:
Read More…

Adapter

„Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

Design Patterns: Elements of Reusable Object-Oriented Software

As you may have noticed, with Singleton, we reached the end of the creational patterns. From now on, we’ll consider the benefits of each so-called structural pattern. You don’t have to be a genius to find out what structural patterns are involved in: defining the composition of larger structures, built from objects.

The first one in the list is called Adapter (you may (and I have) known it as Wrapper). It comes handy when you are dealing with incompatible types (to be strict, interfaces). There are four players in the adapter pattern:

  • Target: that is, what the client can use, the shape we need to from the adaptee.
  • Client: our code which works with the Target.
  • Adaptee: an existing interface, that the client needs to use
  • Adapter: the class which acts as a wrapper, and adapts Adaptee to Target.

Maybe I haven’t described the problem in the best available way, so let’s see a code sample for this one:
Read More…

Singleton

“Ensure a class only has one instance, and provide a global point of access to it.”

Design Patterns: Elements of Reusable Object-Oriented Software

The Singleton pattern is something really simple. Let’s assume you have a class, which represents your data access layer, as a whole. As you might guess, a DAL object can grow quite large, especially when it stores disconnected data, such as in the case of a DataSet. There might be good reasons to have multiple ones instantiated of them, but maybe that’s not the best idea ever.

This is when Singleton pattern comes to place. It ensures that only one and only instance can live of a specific class, and that instance is accessible for every part of your code which needs it for its work. Implementing this behavior in code is very easy, consider the following example:

public sealed class MySingleton
{
                public static readonly MySingleton SoleInstance = new MySingleton();
                //rest of the class
}

Read More…

Prototype

“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.”

Design Patterns: Elements of Reusable Object-Oriented Software

Instantiating a class multiple times can be resource intensive, and can result in repeating the very same code multiple times. Sometimes it is more convenient to copy or clone your existing objects. Fortunately, the .NET Framework has built-in support for these cases, the aforementioned IClonable interface. This interface contains only one method, the Clone, which returns Object. So any time you need to use the Prototype pattern, just implement IClonable, and you are good to go.

A little about the idea: imagine that you are working with a complex class, such as one representing a table of data from a SQL database. You’d do something with it, then you’re in the need of the same data again. Instead of rebuilding the whole object again, you should clone the first one, and call your methods on it. It saves you from writing the same code twice, and the cost of creating a new object on the heap.

To be straightforward, let’s enlist the participants here, too:
Read More…

Factory Method

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”

Design Patterns: Elements of Reusable Object-Oriented Software

A factory method is a method which creates and returns an object. I think this is quite simple, and there are countless examples in the .NET Framework for it. What is it good for? Well, it enforces encapsulation. You have a method to create objects, and it’s far more flexible than just instantiating them through constructors.

The key players in this pattern are:

  • Creator: the abstract base class, which declares the factory method, which returns a type of Product.
  • ConcreteCreator: a concrete implementation of the Creator class, which overrides the factory method in it.
  • Product: the abstract base class or interface for your product types, what creator returns.
  • ConcreteProduct: the concrete implementation of the base Product class, what the ConcreteCreator classes return.

A common practice in the Factory Method pattern is to let the method accept a member of an enumeration, and based on the passed member, return different kinds of objects. Also, it’s quite common to make the constructor of the ConcreteProduct class private, thus enforcing clients to use the factory method.

Read More…

Builder

“Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

Design Patterns: Elements of Reusable Object-Oriented Software

Just like the Abstract Factory pattern, Builder is also a creational pattern, with the same goal: create another (in this case, more complex) objects. To stick with the previous data access example, imagine that you have a class with many properties to set, for example, a DbCommand derivate: SqlCommand. You can build SqlCommand objects with the SqlCommandBuilder class, a derivate of DbCommandBuilder. Now SqlCommandBuilder is very intelligent, it builds a complete command object from just a SqlDataAdapter object (which has everything that a command should need: a connection object and a select command object).
Read More…

Abstract Factory

“Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”

Design Patterns – Elements of Reusable Object-Oriented Software

So let’s begin revising the “traditional” object-oriented design patterns. I’m going to stick closely to the book, so the order of posts will be the same as the order in the book.

Abstract Factory is a creational pattern. It means that its sole purpose of such a class is to create another objects/classes. An Abstract Factory pattern has the following participants:

  • Abstract base factory class/interface
  • Concrete factory subclasses derived from the base class, implements the interface
  • Abstract product: the abstract base class of the products to be created
  • Concrete product: the concrete implementation of the abstract product.
  • Client: uses the abstract factory and the abstract product classes, without further knowledge of their concrete implementations.

Read More…

Blog reopened

Welcome back everybody! As you can guess I was a little overwhelmed in the past days, so I’ve lacked the necessary time to write articles in a continuous manner, but that ends today.

The sad part first: I’ve lost my interest in WCF a while ago, so there won’t be any post about it till something extraordinary happens. The happier: I started to work with ASP.NET MVC, and it was love at the first sight. Producing such clean HTML, and the total control over how’s it rendered (not to say anything about built-in URL routing)! But what was far more appealing is the Model-View-Controller pattern.

I found out that I don’t know enough about design patterns as a whole. That gave me the apropos to order the Design Patterns book written by the Gang of Four. From now on, till there won’t be any more left, I post one or two patterns with C# code examples a day, from tomorrow. Be sure to check back!