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); } } } |
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"); } } } |
http://www.dofactory.com/Patterns/PatternAdapter.aspx
No comments:
Post a Comment