Subscribe!

Don't forget to...

 Subscribe

Friday, October 7, 2011

Adapter Design Pattern

The adapter pattern is an extremely useful pattern for a few reasons. The reason I like it so much is because if you understand it, then you understand the concept of Dependency Inversion (the "D" in SOLID object-oriented design).

Dependency Inversion is an object-oriented principle which states that in code, higher level modules should not depend on lower level modules. Instead, lower level modules should depend on higher level ones. Let's say you've got one higher level object that requires a lower level object to do it's job. But the lower-level object is likely to change or be swapped out for another. Here's the bad way to do it:

namespace HigherLevelModule
{
    public class HigherLevelObject
    {
        ......

        public void Run()
        {
            LowerLevelObject obj = new LowerLevelObject();
            
            string result = obj.GetSomething();
            Console.WriteLine(result);
        }
    }
}

namespace LowerLevelModule
{
    public class LowerLevelObject
    {
        ......

        public string GetSomething()
        {
            return new String("you got me!");
        }
    }
}



Now, the reason that this is bad, is because it makes the task of swapping out the lower level object more difficult than it needs to be. The higher level depends on the lower level! LowerLevelModule can be compiled without HigherLevelModule but not vice versa - which is the opposite of what we want.

So here's a better version:

namespace HigherLevelModule
{
    public class HigherLevelObject
    {
        ......

        public void Run()
        {
            IAdapter obj = LowerLevelObjectFactory
                                .GetInstance()
                                .GetLowerLevelObject();
            
            string result = obj.GetSomething();
            Console.WriteLine(result);
        }
    }

    public interface IAdapter
    {
        string GetSomething();
    }

    public class LowerLevelObjectFactory
    {
        private static LowerLevelObjectFactory Factory =
                                new LowerLevelObjectFactory();
        
        private LowerLevelObjectFactory()
        {
        }

        public static LowerLevelObjectFactory GetInstance()
        {
            return Factory;
        }

        public IAdapter GetLowerLevelObject()
        {
            return new LowerLevelObjectA();
        }

    }
}

namespace LowerLevelModule
{
    public class LowerLevelObjectA : IAdapter
    {
        ......

        public string GetSomething()
        {
            return new String("you got A!");
        }
    }

    public class LowerLevelObjectB : IAdapter
    {
        ......

        public string GetSomething()
        {
            return new String("this time you got B!");
        }
    }
}

With this new code, the higher level doesn't care what the actual type of the ILowerLevel instance is, it just cares that it has a GetSomething() method, which is guaranteed by the ILowerLevel contract. Now the higher level can use the factory method to create lower level objects all over the place, and if the type of the lower level object ever has to be changed, there's only one line of code that needs to be changed:

public IAdapter GetLowerLevelObject()
{
    return new LowerLevelObjectB();
}


Now THAT's maintainability. Wurd.

Wednesday, October 5, 2011

Command Design Pattern

The command pattern is best used when you have a command that must be executed by one object, while another object has the responsibility of deciding WHEN that command will be executed.

The three entities associated with the command pattern are:

client: the object that CREATES the command object and assigns it's receiver receiver: the object that HAS the method that will be run invoker: the object that DECIDES WHEN the command will be run
Now let's look at an example. You have an IDE, and the 'undo' command is extremely important. Every action that is performed on the IDE has a method called undo() on it. But the actions have to be stored somewhere after they perform their task though, so that it's possible to call the undo() methods later, right? The solution is to push each action onto a stack when it's run, and register a listener for the 'undo' keyboard-combination/menu-item. The listener will pop() the stack, and invoke the popped action's undo method...voila!

So what are the entities? The module in the IDE that pushes each action onto the stack is the client, each action on the stack is the receiver, and the listener is the invoker. The actions can also be thought of as command objects.

Tuesday, October 4, 2011

Flyweight Design Pattern

So you have a group of objects that can be reused, but each time you use one you have to create it first. The problem is that instantiating these types of objects is expensive, and you don't want to instantiate the same kind every time you need it. Enter Flyweight design pattern. With this pattern, the trick is to create a new object only when you've never created that same type of object before - if you HAVE created it before, then simply look it up and use the one that's already instantiated. Here's some code:

public class Flyweight
{
    public static Dictionary _Table = new Dictionary();

    public ISomething GetSomething(int key)
    {
        ISomething something;
        if(_Table.TryGetValue(key, ref something))
        {
            return something;
        }
        else
        {
            something = new Something(key);
            _Table.Add(key, something);
            return something;
        }
    }
}

What this code does is ensure that the only time an object of type ISomething is instantiated is when there's a type requested that hasn't been requested before. Otherwise it'll return the one that was requested before. The GOOD: saves clock cycles by instantiating each type only once. The potentially BAD: uses more memory than creating new instances on the fly. Cheers.

Monday, October 3, 2011

Factory Design Pattern

The factory pattern is used when you want to separate the creation of objects from where they'll be used.

For example, say you have one object that must get a Triangle object and draw it on screen. It doesn't care about what the triangle's state is, just that it has a void Draw() method. Suppose further that you have many types of triangles, and they can all be 'drawn' onscreen. In order to separate the creation of triangle objects from the caller, we would use the Factory Design Pattern:

1.) Create an interface called ITriangle, with one method : void Draw()
2.) Have all types of Triangle implement ITriangle.
3.) Create an interface called ITriangleFactory with 1 method: ITriangle GetTriangle()
4.) Create a concrete 'factory' class for each type of Triangle, each of which implements ITriangleFactory, and returns a new instance of their respective triangle in their implementations of GetTriangle()...since each Triangle type implements ITriangle, each factory can return whatever type of triangle it wants.

Now you can easily add triangle types in the future and change the type that is drawn by the caller, without changing every line of code that references the triangle:

public void callerMethod(ITriangleFactory factory){
    ITriangle myNewTriangle = factory.GetTriangle();
    myNewTriangle.Draw();
}

In the above code, if you want to change the type of triangle drawn, simply change the type of factory passed into callerMethod(). The rest is already taken care of.

Cheers.