Tigraine

Daniel Hoelbling-Inzko talks about programming

Using Extension Methods as a Factory Method for an Adapter

Posted by Daniel Hölbling on October 2, 2008

Sometimes you have existing code you don't want to change. And sometimes you need to write libraries that consume these old legacy objects as input to function.
No need to say that it's usually a bad idea to couple your code to not properly tested and poorly designed legacy code.

So it's generally a good idea to abstract it away from new code and try to mask the old objects through adapters and interfaces from being too tightly coupled to your new code.

Either way, you're trying to put square blocks into round holes. And the adapter classes need to be initialized by your callers every time your class gets used.

    public class LegacyFoo
    {
        public void SomeFoo()
        {}
    }
    public interface IFoo
    {
        void Foo();
    }
    public class FooAdapter : IFoo
    {
        private readonly LegacyFoo Foo_;
        public FooAdapter(LegacyFoo foo)
        {
            Foo_ = foo; }
        public void Foo()
        { Foo_.SomeFoo(); }
    }
    public class FooConsumer
    {
        public void DoSomethingWithOldFoo(IFoo oldFoo)
        { oldFoo.Foo(); }
    }

So instead of providing yet another Factory that constructs the adapter object, you could instead just put the factory method onto the legacy object by using an extension method:

    public static class FooExtensions
    {
        public static IFoo GetFooAdapter(this LegacyFoo foo)
        { return new FooAdapter(foo); }
    }

Now your callers can conveniently construct the Adapter object by calling:

LegacyFoo foo = new LegacyFoo();
foo.GetFooAdapter()

Filed under net, programmierung, patterns
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more