How to use Dependency Injection without breaking encapsulation?

前端 未结 9 651
囚心锁ツ
囚心锁ツ 2020-12-23 09:24

How can i perform dependency injection without breaking encapsulation?

Using a Dependency Injection example from Wikipedia:

public Car {
    public f         


        
9条回答
  •  盖世英雄少女心
    2020-12-23 10:14

    This is where I think you must use dependency injection containers that let you encapsulate the creation of your car, without letting your client callers need to know how to create it whatsoever. Here's how symfony solved this problem (even though it is not the same language, principles remain the same):

    http://components.symfony-project.org/dependency-injection/documentation

    there is a section on dependency injection containers.

    To make it short and summarize it all quoted from the documentation page directly:

    When using the container, we just ask for a mailer object [This would be your car in your example], and we don't need to know anything about how to create it anymore; all the knowledge about how to create an instance of the mailer [car] is now embedded into the container.

    It the hope that it helps you

提交回复
热议问题