开发者

static factory method (Spring)

What is the advantage and use to Instantiate a bean i开发者_Python百科n Spring Framework using a static factory method?


The advantages of using the static factory method for bean instantiation don't necessarily come from Spring which is just an IoC container.

Some suggestions from Effective Java Idiom#1, providing static factory provides the following advantages over creating objects from constructor:

  1. Gives your methods a more expressive name, than the Constructor.
  2. You can, skip actual object creation and provide proxies.
  3. You can return a subtype of the method return type.

I find the greatest advantage of this idiom in having named methods with similar signatures.

for example if you have:

    Person {
    String name;
    String[] booksAuthored;
    //... constructors, getters, setters
  }

Then you can create instances by calling these:

Person joshTheProgrammer = Person.createByName("Joshua Bloch");

or

Person joshTheAuthor = Person.createByBookName("Effective Java");

you can't do that when using the constructors, as you can have only one constructor that accepts a String.


I'd like to add the fact that maybe some thirdparty libraries simply rely on using factory methods. So you probably don't want (or even can't) change the code to be simply DI compatible. So in this case you can integrate legacy code with dependency injection although it was not designed to be used in such a scenarion initially.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜