简体   繁体   English

这是什么设计模式?

[英]What Design Pattern is this?

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. 我喜欢称之为GuiceStateHolder类,但我不确定。

是的我同意这不是任何模式的规范示例,但我看到依赖注入的元素(显然,它使用的是Guice)和工厂方法( getInstance() )。

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. 模式(Singleton除外)通常表示比设置某个可更改的默认实现更复杂的关系。

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. 除非它是一种与单个习语有很强连接的模式,否则不可能从代码中反向设计模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM