开发者

How to choose between methods of acquiring dependencies?

开发者 https://www.devze.com 2023-01-12 16:48 出处:网络
I\'ve seen at least three ways of acquiring dependencies in a Java object without coupling the object to the creation of the dependency;

I've seen at least three ways of acquiring dependencies in a Java object without coupling the object to the creation of the dependency;

Dependency Injection - some framework injects a required object into another object based on an external configuration, example: Spring managed beans

Dependency Lookup - a class looks up a required dependency in some kind of directory service, example: JNDI lookups in a Java EE container

Static Factories - an object in a global scope provides instances on demand - the standard Java SE APIs seem to be littered with these, example: java.util.Logger.getLogger(name), java.util.Calendar.getInstance()

What guidance can you provide as to wh开发者_高级运维ich is most appropriate for a situation?


I prefer dependency injection, because the object need not know how it acquires the references it needs.

Dependency lookup still requires the object to know about the lookup service and its URL.

Static factories are similar to lookup services.


I prefer dependency injection.

When I talk about DI with Spring Framework I see following

  1. It's supported by IDEs (error check, visualization).
  2. You can setup other needed stuff like AOP, properties loading, ...
  3. You have big config possibilities - XML, annotation, JavaConfig
  4. Can be use also in desktop application.

These outbalance every negatives like dependency on another library. Why should I use another approach?


This really depends on the context. If you are writing a self-contained Maths API you might want to use static factories because the code will be less verbose, setup-free and maybe more efficient. If you need to access/provide a remote dependency, a JNDI/LDAP lookup, or ESB messaging would work well. For injecting your services/DAO's/datasources into your typical enterprise server code you'd be better off using one of the common D.I. frameworks like Google Guice or Spring.

There is no single 'best' solution in software design; it's always a tradeoff.

0

精彩评论

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

关注公众号