stackh34p
stackh34p

Reputation: 9009

Is this a design pattern and does it have a common name?

I have a library with only interfaces and basic objects, lets call it API. The API has a few known implementations, that may increase in number for the needs of an application. The application can use only one implementation at a time. I have another library, lets call it PROXY, which provides a basic implementation of the API library, and it delegates the logic to a real implementation of the API. The real implementation is provided by configuration and the PROXY library takes care of creating the appropriate real classes and wrapping them. The idea is to use the API and PROXY libraries in my code, so that I can change implementations without recompiling the application - just changing the configuration and providing the real implementation library in the classpath. Here is an example code in C#:

API:

public interface IFoo
{
    void Bar();
}

PROXY:

public class Foo : IFoo
{
    private IFoo _realFoo;

    public Foo()
    {
        _realFoo = ...; // Assume reading the config and creating the real implementation with reflection here.
    }

    void Bar()
    {
        _realFoo.Bar();
    }
}

Real Implementation:

public class RealFoo : IFoo
{
    void Bar()
    {
        // Some specific logic 
    }
}

I guess the Foo class above uses Decorator Pattern to wrap arround the real implementation. I am more interested if the whole approach has a specific name?

Upvotes: 0

Views: 125

Answers (3)

Maziar Taheri
Maziar Taheri

Reputation: 2338

I think that you have mixed Proxy pattern with some kind of Factory Method Pattern.

In plain proxy pattern, the proxy object does not create the main target itself. But instead some Factory class which is supposed to create objects of target type, creates the target instance and passes it to a proxy instance and finally returns the proxy.

There are also different ways to create proxy objects. take a look to Castle Dynamic Proxy for instance, -- That is intended to provide ASPECTS.

Upvotes: 1

tcarvin
tcarvin

Reputation: 10855

This is not a use of the Decorator pattern for a number of reasons, most importantly in intent.

It is a Proxy. Genericly the proxy pattern

Provides a surrogate or placeholder for another object to control access to it

The fact that you are using it to dynamically load your implementation and therefore have a loose coupling with your implementation based on configuration also make it similar to Dependency Injection. Your version differs in that you have a proxy object in the middle. If instead your client held a reference to RealFoo, but this reference was obtained via the kind of mechanisms you are talking about, then that would more closely match Dependency Injection.

Upvotes: 3

mynkow
mynkow

Reputation: 4548

I use IoC/DI for exactly the same thing and Castle Windsor as my IoC container.

http://martinfowler.com/articles/injection.html

Upvotes: 1

Related Questions