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

No comments: