Monday, April 28, 2008

Composite Pattern

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Say you have several different types of objects that together form a structure, for example a tree. Take a look at my example below:

Class: Branch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
namespace Composite
{
    public class Branch
    {
        private readonly List<object> _Children;

        public Branch()
        {
            _Children = new List<object>();
        }

        public void Add(object item)
        {
            _Children.Add(item);
        }

        public void Display()
        {
            Display(1);
        }
        public void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Branch");
            level++;
            foreach (object child in _Children)
            {
                Branch branch = child as Branch;
                if (branch != null)
                {
                    branch.Display(level);
                    continue;
                }
                Leaf leaf = child as Leaf;
                if (leaf != null)
                {
                    leaf.Display(level);
                    continue;
                }
                Apple apple = child as Apple;
                if (apple != null)
                {
                    apple.Display(level);
                    continue;
                }
            }
        }
    }
}
Class: Leaf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Composite
{
    public class Leaf
    {
        public void Display()
        {
            Display(1);
        }
        public void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Leaf");
        }
    }
}
Class: Apple
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Composite
{
    public class Apple
    {
        public void Display()
        {
            Display(1);
        }
        public void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Apple");
        }
    }
}
As you can see each object has a Display method, but the Display method of the Branch object is also calling its children’s Display method. And to be able to do that it needs to know what type of object it is. That results in the ugly if type name is object as type validation. The Composite Pattern is there to solve that. Take a look below:
Interface: IDisplayItem
1
2
3
4
5
6
7
8
namespace Composite
{
    public interface IDisplayItem
    {
        void Display();
        void Display(int level);
    }
}
Class: DisplayItem : IDisplayItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Composite
{
    public class DisplayItem : IDisplayItem
    {
        public virtual void Display()
        {
            Display(1);
        }
        public virtual void Display(int level)
        {
            throw new NotImplementedException();
        }
    }
}
Class: Branch : DisplayItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
namespace Composite
{
    public class Branch : DisplayItem
    {
        private readonly List<DisplayItem> _Children;

        public Branch()
        {
            _Children = new List<DisplayItem>();
        }

        public void Add(DisplayItem item)
        {
            _Children.Add(item);
        }

        public override void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Branch");
            level++;
            foreach (DisplayItem child in _Children)
            {
                child.Display(level);
            }
        }
    }
}
Class: Leaf : DisplayItem
1
2
3
4
5
6
7
8
9
10
namespace Composite
{
    public class Leaf : DisplayItem
    {
        public override void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Leaf");
        }
    }
}
Class: Apple : DisplayItem
1
2
3
4
5
6
7
8
9
10
namespace Composite
{
    public class Apple : DisplayItem
    {
        public override void Display(int level)
        {
            Console.WriteLine(new string('-', level) + " Apple");
        }
    }
}
See how much nicer this deals with the different child items? Now the Branch does not need to worry about what type of objects its children are, they all inherited from DisplayItem. I hope you found these examples helpful. Also take a look at the following links:

http://www.dofactory.com/Patterns/PatternComposite.aspx
http://sourcemaking.com/design_patterns/composite

Thursday, April 24, 2008

Specification Pattern using Spring.Net

After creating my previous post about the Specification Pattern I was thinking that it would be cool if we could use Spring.Net to actually provide the specification. Well after a little looking around I found the solution. I’ll only post the modifications that I made to the code from my last post. Take a look at the example below:

Class: SpecificationFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace Specification
{
    public class SpecificationFactory
    {
        public ISpecification GetSpecification()
        {
            using (IApplicationContext ctx = ContextRegistry.GetContext())
            {
                return (ctx.GetObject("Specification") as ISpecification);
            }
        }
    }
}
Class: SelectFromList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace Specification
{
    public class SelectFromList
    {
        private readonly List<IUser> _Users;

        public SelectFromList()
        {
            _Users = new List<IUser>();
            _Users.Add(new User() { FirstName="Mark", LastName="Nijhof", Age=31 });
            _Users.Add(new User() { FirstName = "Mona", LastName = "Nijhof", Age = 30 });
            _Users.Add(new User() { FirstName = "Milo", LastName = "Nijhof", Age = 2 });
            _Users.Add(new User() { FirstName = "Thalia", LastName = "Nijhof", Age = 1 });
        }

        public List<IUser> GetUsers(ISpecification specification)
        {
            List<IUser> result = new List<IUser>();
            foreach (IUser user in _Users)
            {
                if (specification.IsSatisfiedBy(user))
                {
                    result.Add(user);
                }
            }
            return (result);
        }
    }
}
File: App.Config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="config://spring/objects" />
    </context>
    <objects xmlns="http://www.springframework.net">

      <object id="Specification" type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core">
        <property name="TargetObject" ref="StartWith"/>
        <property name="TargetMethod" value="And"/>
        <property name="Arguments" ref="JongerThanWrapper" />
      </object>

      <object id="JongerThanWrapper" type="Spring.Objects.Factory.Config.MethodInvokingFactoryObject, Spring.Core">
        <property name="TargetObject" ref="JongerThan"/>
        <property name="TargetMethod" value="Or"/>
        <property name="Arguments" ref="OlderThan" />
      </object>

      <object name="StartWith" type="Specification.StartWith, Specification" />
      <object name="OlderThan" type="Specification.OlderThan, Specification" />
      <object name="JongerThan" type="Specification.JongerThan, Specification" />
    </objects>
  </spring>
</configuration>
As you can see we created an extra class SpecificationFactory that would request the correct specification implementation from Spring.Net, we changed the GetUsers method from the SelectFromList class to use the SpecificationFactory class. Now take a close look at the App.Config, the object name that the SpecificationFactory is requesting is Specification. Specification is executing the 'And' method on object StartWith and is returning the value to the SpecificationFactory. As you may see the 'And' method is requiring another ISpecification object, it is pointing to JongerThanWrapper object. And so on until we get the exact same behavior that we had in my previous post, only now completely configurable using Spring.Net. Isn’t this great.

I hope you found these examples helpful. Also take a look at the following links:

http://www.springframework.net/
http://www.springframework.net/doc-1.1-P2/api/html/Spring.Objects.Factory.Config.MethodInvokingFactoryObject.html

Specification Pattern

The Specification pattern is a very powerful design pattern which can be used to remove a lot of cruft from a class’s interface while decreasing coupling and increasing extensibility. It’s primary use is to select a subset of objects based on some criteria, and to refresh the selection at various times. Take a look at the example below:

Interface: IUser
1
2
3
4
5
6
7
8
9
namespace Specification
{
    public interface IUser
    {
        string FirstName { get; set; }
        string LastName { get; set; }
        int Age { get; set; }
    }
}
Class: SelectFromList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace Specification
{
    public class SelectFromList
    {
        private readonly List<IUser> _Users;

        public SelectFromList()
        {
            _Users = new List<IUser>();
            _Users.Add(new User() { FirstName="Mark", LastName="Nijhof", Age=31 });
            _Users.Add(new User() { FirstName = "Mona", LastName = "Nijhof", Age = 30 });
            _Users.Add(new User() { FirstName = "Milo", LastName = "Nijhof", Age = 2 });
            _Users.Add(new User() { FirstName = "Thalia", LastName = "Nijhof", Age = 1 });
        }

        public List<IUser> GetUsers()
        {
            List<IUser> result = new List<IUser>();
            foreach (IUser user in _Users)
            {
                if (user.FirstName.StartsWith("M") &&
                    (user.Age > 10 || user.Age < 2))
                {
                    result.Add(user);
                }
            }
            return (result);
        }
    }
}
Below here you will see some preparation for the Specification Pattern, this might look like a lot of work but when dealing with a lot of these selection statements you will soon see the benefit of it, especially when you need to make changes to what you are selecting on.
Interface: ISpecification
1
2
3
4
5
6
7
8
9
10
11
namespace Specification
{
    public interface ISpecification
    {
        bool IsSatisfiedBy(IUser candidate);

        ISpecification And(ISpecification other);
        ISpecification Or(ISpecification other);
        ISpecification Not(ISpecification other);
    }
}
Class: Specification : ISpecification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Specification
{
    public class Specification : ISpecification
    {
        public virtual bool IsSatisfiedBy(IUser candidate)
        {
            throw new NotImplementedException();
        }
        public ISpecification And(ISpecification other)
        {
            return new AndSpecification(this, other);
        }
        public ISpecification Or(ISpecification other)
        {
            return new OrSpecification(this, other);
        }
        public ISpecification Not(ISpecification other)
        {
            return new NotSpecification(this, other);
        }
    }
}
Class: AndSpecification : Specification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Specification
{
    public class AndSpecification : Specification
    {
        private readonly ISpecification _One;
        private readonly ISpecification _Other;
        
        public AndSpecification(ISpecification one, ISpecification other)
        {
            _One = one;
            _Other = other;
        }

        public override bool IsSatisfiedBy(IUser candidate)
        {
            return _One.IsSatisfiedBy(candidate) && _Other.IsSatisfiedBy(candidate);
        }
    }
}
Class: OrSpecification : Specification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Specification
{
    public class OrSpecification : Specification
    {
        private readonly ISpecification _One;
        private readonly ISpecification _Other;

        public OrSpecification(ISpecification one, ISpecification other)
        {
            _One = one;
            _Other = other;
        }

        public override bool IsSatisfiedBy(IUser candidate)
        {
            return _One.IsSatisfiedBy(candidate) || _Other.IsSatisfiedBy(candidate);
        }
    }
}
Class: NotSpecification : Specification
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Specification
{
    public class NotSpecification : Specification
    {
        private readonly ISpecification _One;
        private readonly ISpecification _Other;

        public NotSpecification(ISpecification one, ISpecification other)
        {
            _One = one;
            _Other = other;
        }

        public override bool IsSatisfiedBy(IUser candidate)
        {
            return _One.IsSatisfiedBy(candidate) && !_Other.IsSatisfiedBy(candidate);
        }
    }
}
Now take a look at how the Specification Pattern makes this much cleaner:
Class: StartWith : Specification
1
2
3
4
5
6
7
8
9
10
namespace Specification
{
    public class StartWith : Specification
    {
        public override bool IsSatisfiedBy(IUser candidate)
        {
            return (candidate.FirstName.StartsWith("M"));
        }
    }
}
Class: OlderThan : Specification
1
2
3
4
5
6
7
8
9
10
namespace Specification
{
    public class OlderThan : Specification
    {
        public override bool IsSatisfiedBy(IUser candidate)
        {
            return (candidate.Age > 10);
        }
    }
}
Class: JongerThan : Specification
1
2
3
4
5
6
7
8
9
10
namespace Specification
{
    public class JongerThan : Specification
    {
        public override bool IsSatisfiedBy(IUser candidate)
        {
            return (candidate.Age < 2);
        }
    }
}
Class: SelectFromList
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace Specification
{
    public class SelectFromList
    {
        private readonly List<IUser> _Users;

        public SelectFromList()
        {
            _Users = new List<IUser>();
            _Users.Add(new User() { FirstName="Mark", LastName="Nijhof", Age=31 });
            _Users.Add(new User() { FirstName = "Mona", LastName = "Nijhof", Age = 30 });
            _Users.Add(new User() { FirstName = "Milo", LastName = "Nijhof", Age = 2 });
            _Users.Add(new User() { FirstName = "Thalia", LastName = "Nijhof", Age = 1 });
        }

        public List<IUser> GetUsers(ISpecification specification)
        {
            List<IUser> result = new List<IUser>();
            foreach (IUser user in _Users)
            {
                if (specification.IsSatisfiedBy(user))
                {
                    result.Add(user);
                }
            }
            return (result);
        }
    }
}
Usage
1
2
3
4
5
ISpecification startsWith = new StartWith();
ISpecification olderThan = new OlderThan();
ISpecification jongerThan = new JongerThan();

SFL.GetUsers(startsWith.And(olderThan.Or(jongerThan)));
When you look at the new SelectFromList class and how this is being used than you can see that it became much easier to extend or change the selection criteria.

I hope you found these examples helpful. Also take a look at the following links:

http://www.martinfowler.com/apsupp/spec.pdf
http://www.mattberther.com/2005/03/25/the-specification-pattern-a-primer/
http://en.wikipedia.org/wiki/Specification_pattern

Fluent Interfaces

What is a Fluent Interface, well is basically means that you can execute a method on an object and that that object would return itself to the caller, by doing so the client can chain multiple commands to each other. This will make the code (if implemented correctly) easier to read, please take a look at the example of a Fluent Interface below:

Interface: IOrder
1
2
3
4
5
6
7
8
9
namespace FluentInterfaces
{
    public interface IOrder
    {
        IOrder ShipAddress(IAddress address);
        IOrder BillAddress(IAddress address);
        IOrder AddItem(IItem item);
    }
}
Interface: IAddress
1
2
3
4
5
6
7
8
9
namespace FluentInterfaces
{
    public interface IAddress
    {
        IAddress Street(string street);
        IAddress PostalCode(string postalCode);
        IAddress City(string city);
    }
}
Interface: IOrder
1
2
3
4
5
6
7
8
9
namespace FluentInterfaces
{
    public interface IItem
    {
        IItem ProductID(int id);
        IItem Price(double price);
        IItem NubmerOfItems(int count);
    }
}
Class: Order : IOrder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace FluentInterfaces
{
    public class Order : IOrder
    {
        private IAddress _ShipAddress;
        private IAddress _BillAddress;
        private readonly List<IItem> _Items;

        public Order()
        {
            _Items = new List<IItem>();
        }

        public IOrder ShipAddress(IAddress address)
        {
            _ShipAddress = address;
            return (this);
        }
        public IOrder BillAddress(IAddress address)
        {
            _BillAddress = address;
            return (this);
        }
        public IOrder AddItem(IItem item)
        {
            _Items.Add(item);
            return (this);
        }
    }
}
Class: Address : IAddress
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace FluentInterfaces
{
    public class Address : IAddress
    {
        private string _Street;
        private string _PostalCode;
        private string _City;

        public IAddress Street(string street)
        {
            _Street = street;
            return (this);
        }
        public IAddress PostalCode(string postalCode)
        {
            _PostalCode = postalCode;
            return (this);
        }
        public IAddress City(string city)
        {
            _City = city;
            return (this);
        }
    }
}
Class: Item : IItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace FluentInterfaces
{
    public class Item : IItem
    {
        private int _Id;
        private double _Price;
        private int _Count;

        public IItem ProductID(int id)
        {
            _Id = id;
            return (this);
        }
        public IItem Price(double price)
        {
            _Price = price;
            return (this);
        }
        public IItem NubmerOfItems(int count)
        {
            _Count = count;
            return (this);
        }
    }
}
Class: Main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
namespace FluentInterfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            IOrder order = new Order()
                .ShipAddress(new Address()
                    .Street("Burggraaf 12")
                    .PostalCode("7371CW")
                    .City("Loenen"))
                .BillAddress(new Address()
                    .Street("Burggraaf 12")
                    .PostalCode("7371CW")
                    .City("Loenen"))
                .AddItem(new Item()
                    .ProductID(1)
                    .Price(15.40)
                    .NubmerOfItems(2))
                .AddItem(new Item()
                    .ProductID(132)
                    .Price(101.10)
                    .NubmerOfItems(1));
        }
    }
}
As you can see the actual creation of the Order and all of its properties has been simplified significantly and has improved readability. You can now directly see what this order is about. Indentation is only done for readability it could have been done like this:
Class: Main
1
2
3
4
5
6
7
8
9
10
namespace FluentInterfaces
{
    class Program
    {
        static void Main(string[] args)
        {
            IOrder order = new Order().ShipAddress(new Address().Street("Burggraaf 12").PostalCode("7371CW").City("Loenen")).BillAddress(new Address().Street("Burggraaf 12").PostalCode("7371CW").City("Loenen")).AddItem(new Item().ProductID(1).Price(15.40).NubmerOfItems(2)).AddItem(new Item().ProductID(132).Price(101.10).NubmerOfItems(1));
        }
    }
}
I hope you found these examples helpful. Also take a look at the following links:

http://martinfowler.com/bliki/FluentInterface.html
http://www.bofh.org.uk/articles/2005/12/21/fluent-interfaces

Wednesday, April 23, 2008

Adapter Pattern

The pattern states: the Adapter pattern adapts one interface for a class into one that a client expects. An adapter allows classes to work together that normally could not because of incompatible interfaces by wrapping its own interface around that of an already existing class. Take a look at the example below:

Class: Client
1
2
3
4
5
6
7
8
9
10
namespace Adapter
{
    public class Client
    {
        public void StartWorkerProcess(IWorker worker)
        {
            worker.StartWork();
        }
    }
}
Interface: IWorker
1
2
3
4
5
6
7
namespace Adapter
{
    public interface IWorker
    {
        void StartWork();
    }
}
Class: Worker : IWorker
1
2
3
4
5
6
7
8
9
10
namespace Adapter
{
    public class Worker : IWorker
    {
        public void StartWork()
        {
            Console.WriteLine("Start working");
        }
    }
}
Interface: IOtherWorker
1
2
3
4
5
6
7
namespace Adapter
{
    public interface IOtherWorker
    {
        void Start(string message);
    }
}
Class: OtherWorker : IOtherWorker
1
2
3
4
5
6
7
8
9
10
namespace Adapter
{
    public class OtherWorker : IOtherWorker
    {
        public void Start(string message)
        {
            Console.WriteLine("Start working on: " + message);
        }
    }
}
You can see that the client is expecting a class with a base type of IWorker and this works fine for the Worker class, but we already have another class OtherWorker in the system that has already implemented the behavior that we are looking for to extend the Client with. But this other worker is accordingly to the IOtherWorker interface, and we cannot change either class because both are already used in existing code (or perhaps the other worker is a third party product). So here comes the Adapter Pattern, take a look below how it will solve our problem:
Class: OtherWorkerAdapter : IWorker
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace Adapter
{
    public class OtherWorkerAdapter : IWorker
    {
        private readonly IOtherWorker _OtherWorker;

        public OtherWorkerAdapter()
        {
            _OtherWorker = new OtherWorker();
        }

        public void StartWork()
        {
            _OtherWorker.Start("Initiated from OtherWorkerAdapter");
        }
    }
}
I hope you found these examples helpful. Also take a look at the following link:

http://www.dofactory.com/Patterns/PatternAdapter.aspx

Strategy Pattern

The pattern states: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Look at the below example demonstrating a potential problem:

Class: Logger
1
2
3
4
5
6
7
8
9
10
namespace Strategy
{
    public class Logger
    {
        public void Log(string logMessage)
        {
            Console.WriteLine(logMessage);
        }
    }
}
You see that this is a really simple logging class logging messages to the console, but now we also want to be able to log to a file. Well you could add a new method to log to a file, but that would mean that all the classes using this Logger class has to change using the new method. So that is a no go. Take a look at the below example using the Strategy Pattern to make this possible without the need to change the client code:
Interface: ILogHandler
1
2
3
4
5
6
7
namespace Strategy
{
    public interface ILogHandler
    {
        void Log(string logMessage);
    }
}
Class: Logger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Strategy
{
    public class Logger
    {
        private ILogHandler _LogHandler;

        public void SetLogHandler(ILogHandler logHandler)
        {
            _LogHandler = logHandler;
        }

        public void Log(string logMessage)
        {
            if (_LogHandler != null)
            {
                _LogHandler.Log(logMessage);
            }
        }
    }
}
When we implement the Logger class in this way than it is according to the Open Closed Principle. We could provide any implementation of the ILogHandler without the need to make any modifications to the class. For example:
Class: ConsoleLogger : ILogHandler
1
2
3
4
5
6
7
8
9
10
namespace Strategy
{
    public class ConsoleLogger : ILogHandler
    {
        public void Log(string logMessage)
        {
            Console.WriteLine(logMessage);
        }
    }
}
Class: FileLogger : ILogHandler
1
2
3
4
5
6
7
8
9
10
namespace Strategy
{
    public class FileLogger : ILogHandler
    {
        public void Log(string logMessage)
        {
            // Log to file functionality
        }
    }
}
I hope you found these examples helpful. Also take a look at the following links:

http://www.dofactory.com/Patterns/PatternStrategy.aspx
http://patnys.com/archive/2008/04/15/strategy-pattern.aspx

Decorator Pattern

The pattern states: Attach additional responsibilities to an object dynamically. The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified. Below is an example of a drawing program that can draw a square:

Interface: IShape
1
2
3
4
5
6
7
namespace Decorator
{
    public interface IShape
    {
        void Draw();
    }
}
Class: Square : IShape
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace Decorator
{
    public class Square : IShape
    {
        private readonly int _Size;

        public Square(int size)
        {
            _Size = size;
        }

        public void Draw()
        {
            Console.WriteLine("Draw square, size:" + _Size);
        }
    }
}
In the next version we want to be able to add a shadow to the square, fill the square with color or do both. We could extend the Square class three times with the individual behavior changes, or we might want to extend it once with all the new behavior and make it optional, but in that case the client needs to know about these options and that will break the Open Closed Principle. So here comes the Decorator Pattern.
Class: Decorator : IShape
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace Decorator
{
    public class Decorator : IShape
    {
        private readonly IShape _Shape;

        public Decorator(IShape shape)
        {
            _Shape = shape;
        }

        public virtual void Draw()
        {
            _Shape.Draw();
        }
    }
}
Class: AddFill : Decorator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace Decorator
{
    public class AddFill : Decorator
    {
        public AddFill(IShape shape) : base(shape)
        {
        }

        public override void Draw()
        {
            base.Draw();
            Console.WriteLine("Add fill to IShape object");
        }
    }
}
Class: AddShadow : Decorator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
namespace Decorator
{
    public class AddShadow : Decorator
    {
        public AddShadow(IShape shape) : base(shape)
        {
        }

        public override void Draw()
        {
            Console.WriteLine("Add shadow to IShape object");
            base.Draw();
        }
    }
}
When you look at the two decoration classes above you see that the AddFill implementation of Draw first calls the base.Draw method while the AddShadow implementation first add its custom addon and than calls the base.Draw method. Now look at how we can implement these Decoration classes:
Class: Main
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace Decorator
{
    class Program
    {
        static void Main(string[] args)
        {
            IShape squareShape = new Square(100);
            squareShape.Draw();
            Console.WriteLine();

            IShape addFill = new AddFill(squareShape);
            addFill.Draw();
            Console.WriteLine();

            IShape addShadow = new AddShadow(addFill);
            addShadow.Draw();

            Console.ReadKey();
        }
    }
}
Output
1
2
3
4
5
6
7
8
Draw square, size:100

Draw square, size:100
Add fill to IShape object

Add shadow to IShape object
Draw square, size:100
Add fill to IShape object
I hope you found these examples helpful. Also take a look at the following links:

http://www.dofactory.com/Patterns/PatternDecorator.aspx
http://www.patnys.com/archive/2008/04/21/decorator-pattern.aspx

Monday, April 21, 2008

Law Of Demeter

The principle states: Each unit should only talk to its friends; Don’t talk to strangers. A method of an object should invoke only the methods of the following kinds of objects:

    1. itself
    2. its parameters
    3. any objects it creates/instantiates
    4. its direct component objects
Below is an example of some code breaking this principle:
Interface: IOrderManager
1
2
3
4
5
6
7
8
9
namespace LOD
{
    public interface IOrderManager
    {
        void AddItemToOrder(IItem item);
        void RemoveItemFromOrder(IItem item);
        void ChangeItemName(IItem item, string name);
    }
}
Interface: IOrder
1
2
3
4
5
6
7
namespace LOD
{
    public interface IOrder
    {
        List<IItem> Items { get; set; }
    }
}
Interface: IItem
1
2
3
4
5
6
7
8
namespace LOD
{
    public interface IItem
    {
        int Id { get; set; }
        string Name { get; set; }
    }
}
Class: Item : IItem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace LOD
{
    public class Item : IItem
    {
        private int _Id;
        private string _Name;

        public int Id
        {
            get { return _Id; }
            set { _Id = value; }
        }
        public string Name
        {
            get { return _Name; }
            set { _Name = value; }
        }
    }
}
Class: Order : IOrder
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace LOD
{
    public class Order : IOrder
    {
        private List<IItem> _Items;

        public List<IItem> Items
        {
            get { return _Items; }
            set { _Items = value; }
        }
    }
}
Class: OrderManager : IOrderManager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace LOD
{
    public class OrderManager : IOrderManager
    {
        private readonly IOrder _Order;

        public OrderManager()
        {
            _Order = new Order();
            _Order.Items = new List<IItem>();
        }

        public void AddItemToOrder(IItem item)
        {
            if (_Order.Items != null)
            {
                if ( ! _Order.Items.Contains(item))
                {
                    _Order.Items.Add(item);
                }
            }
        }
        public void RemoveItemFromOrder(IItem item)
        {
            if (_Order.Items != null)
            {
                if (_Order.Items.Contains(item))
                {
                    _Order.Items.Remove(item);
                }
            }
        }
        public void ChangeItemName(IItem item, string name)
        {
            if (_Order.Items != null)
            {
                if (_Order.Items.Contains(item))
                {
                    _Order.Items[_Order.Items.IndexOf(item)].Name = name;
                }
            }
        }
    }
}
In the above example the OrderManager has the responsibility of adding and removing Items to and from the List collection in the Order class, and even worse it has the responsibility of changing the name of a particular Item inside that collection. This tightly couples the OrderManager to the Order and Item class, if we would change how the Order class is maintaining her Items than we automatically have to change the OrderManager class. The Order should be responsible for its Items, not the OrderManager. Below is the Law Of Demeter implementation of this example:
Interface: IOrder
1
2
3
4
5
6
7
8
9
namespace LOD
{
    public interface IOrder
    {
        void AddItem(IItem item);
        void RemoveItem(IItem item);
        void ChangeItemName(IItem item, string name);
    }
}
Class: Order : IOrder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
namespace LOD
{
    public class Order : IOrder
    {
        private List<IItem> _Items;

        public Order()
        {
            _Items = new List<IItem>();
        }

        public void AddItem(IItem item)
        {
            if (_Items != null)
            {
                if (!_Items.Contains(item))
                {
                    _Items.Add(item);
                }
            }
        }
        public void RemoveItem(IItem item)
        {
            if (_Items != null)
            {
                if (_Items.Contains(item))
                {
                    _Items.Remove(item);
                }
            }
        }
        public void ChangeItemName(IItem item, string name)
        {
            if (_Items != null)
            {
                if (_Items.Contains(item))
                {
                    _Items[_Items.IndexOf(item)].Name = name;
                }
            }
        }
    }
}
Class: OrderManager : IOrderManager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
namespace LOD
{
    public class OrderManager : IOrderManager
    {
        private readonly IOrder _Order;

        public OrderManager()
        {
            _Order = new Order();
        }

        public void AddItemToOrder(IItem item)
        {
            _Order.AddItem(item);
        }
        public void RemoveItemFromOrder(IItem item)
        {
            _Order.RemoveItem(item);
        }
        public void ChangeItemName(IItem item, string name)
        {
            _Order.ChangeItemName(item, name);
        }
    }
}
Now we can change how the Order class is keeping its Items without having to change the OrderManager. One nice rule of thumb is: One dot should be enough.

I hope you found these examples helpful. Also take a look at the following link:

http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf

Dependency Inversion Principle using Spring.Net

This post will continue from my previous post about how to implement the Dependency Inversion Principle. Below you will see an example that is in the same state as where my previous post ended, only I created a different context to make its usefulness more clear.

Interface: IDatabaseOperations
1
2
3
4
5
6
7
8
9
10
namespace SpringDIP
{
    public interface IDatabaseOperations
    {
        void Update(string[] parameters);
        void Delete(int id);

        string[] Select(int id);
    }
}
Class: MsSqlDatabaseProvider : IDatabaseOperations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace SpringDIP
{
    public class MsSqlDatabaseProvider : IDatabaseOperations
    {
        public void Update(string[] parameters)
        {
            // Do a Microsoft SQL Server 2008 specific update
        }
        public void Delete(int id)
        {
            // Do a Microsoft SQL Server 2008 specific delete
        }

        public string[] Select(int id)
        {
            // Do a Microsoft SQL Server 2008 specific select
            return (new string[] { "1", "Microsoft" });
        }
    }
}
Class: DatabaseProviderFactory
1
2
3
4
5
6
7
8
9
10
namespace SpringDIP
{
    public class DatabaseProviderFactory
    {
        public IDatabaseOperations GetDatabaseProvider()
        {
            return (new MsSqlDatabaseProvider());
        }
    }
}
So now what happens when we create another implementation of the IDatabaseOperations interface to interact with an Oracle database instead of the Microsoft SQL Server database. Well than we would have to change the references in the DatabaseProviderFactory and re-compile the classes that where changed / affected. And in that case you would maybe provide two different installers, one for Microsoft and one for Oracle, or maybe you would create a switch in a configuration file and use that value to make a choice between the two options. Anyway ugly is what comes to mind. Below is the solution when using Spring.Net:
Class: DatabaseProviderFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using Spring.Context;
using Spring.Context.Support;

namespace SpringDIP
{
    public class DatabaseProviderFactory
    {
        public IDatabaseOperations GetDatabaseProvider()
        {
            using (IApplicationContext ctx = ContextRegistry.GetContext())
            {
                return(ctx.GetObject("DatabaseProvider") as IDatabaseOperations);
            }
        }
    }
}
File: App.Config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
    </sectionGroup>
  </configSections>

  <spring>
    <context>
      <resource uri="config://spring/objects" />
    </context>
    <objects xmlns="http://www.springframework.net">
      <object name="DatabaseProvider" type="SpringDIP.MsSqlDatabaseProvider, SpringDIP" />
    </objects>
  </spring>
</configuration>
I only needed to change the DatabaseProviderFactory class and add some Spring.Net content in the App.Config file to have my application use the Spring.Net framework. In the DatabaseProviderFactory class I am refering to the Spring.Net configuration name DatabaseProvider and in this case Spring.Net will provide the MsSqlDatabaseProvider. In the future I will only need to provide the new DLL with for example the OracleDatabaseProvider and change the one line in the App.Config file, no need to re-compile.

I hope you found these examples helpful. Also take a look at the following links:

http://springframework.net/
http://www.developer.com/net/csharp/article.php/10918_3722931_1