views:

231

answers:

3

I know that everything we do in programming can be described as design pattern(even abstract method has design pattern called template method)


public class Guicer extends AbstractModule {
    private static Injector injector = Guice.createInjector(new Guicer());

    public static void setInjector(Injector injector) {
        Guicer.injector = injector;
    }

    public static <T> T getInstance(Class<T> c) {
        return injector.getInstance(c);
    }

    @Override
    protected void configure() {

    }
}

What design patterns are used in this code? Id like to call that class GuiceStateHolder, but im not sure about it.

+1  A: 

This snippet doesn't represent a design-pattern from the catalog. Patterns (except Singleton) usually represent more complex relationship than setting a changeable default implementation of something.

stacker
using setInjector you can change the implementation of injector that is used in a whole application. plus I think getInstance is some kind of Fasade. This page doesnt have all the design patterns just a few common known.
01
There's no definite list of "all the design patterns".
Andreas Brinck
@Andreas Brink - I agree one need sveral catalogs like http://martinfowler.com/eaaCatalog/ , GoF etc.
stacker
+2  A: 

Yeah I agree this isn't really a canonical example of any pattern, but I see elements of dependency injection (obviously, it's using Guice), and a factory method (getInstance()).

Sean Owen
@Andreas: If the `.getInstance()` always returns the same Object (which I assume it does), then yes this is a singleton. However if it potentially returns separate instances (*DI'd object gets updated/replaced, perhaps?*) then it's a factory method.
Esko
@Esko Yep, I misread the original code, that's why I deleted my comment.
Andreas Brinck
@Andreas: SO apparently caches comments for a bit so it was showing for me after I had posted my reply. No worries tho' :)
Esko
+1  A: 

Well, I'd call this bit:

private static Injector injector = Guice.createInjector(new Guicer());

public static void setInjector(Injector injector) {
    Guicer.injector = injector;
}

a write-only global variable.

And here:

public static <T> T getInstance(Class<T> c) {
    return injector.getInstance(c);
}

you replace an instance method with a global function. So you've basically got a global variable, which anyone can write, but you can only call the one method on it. Since injector has more in its interface, it is possibly some kind of restricted façade.

But they are more idioms than a pattern - a pattern would also describe what it is trying to achieve in terms of desired behaviour, whereas an idiom is how you go about doing something in code.

Unless it is a pattern which has a very strong connection to a single idiom, then it is impossible to reverse-engineer patterns from code.

Pete Kirkham