How to use Dependency Injection without breaking encapsulation?

前端 未结 9 632
囚心锁ツ
囚心锁ツ 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:11

    Factories and interfaces.

    You've got a couple of questions here.

    1. How can I have multiple implementations of the same operations?
    2. How can I hide construction details of an object from the consumer of an object?

    So, what you need is to hide the real code behind an ICar interface, create a separate EnginelessCar if you ever need one, and use an ICarFactory interface and a CarFactory class to hide the construction details from the consumer of the car.

    This will likely end up looking a lot like a dependency injection framework, but you do not have to use one.

    As per my answer in the other question, whether or not this breaks encapsulation depends entirely on how you define encapsulation. There are two common definitions of encapsulation that I've seen:

    1. All operations on a logical entity are exposed as class members, and a consumer of the class doesn't need to use anything else.
    2. A class has a single responsibility, and the code to manage that responsibility is contained within the class. That is, when coding the class, you can effectively isolate it from its environment and reduce the scope of the code you're working with.

    (Code like the first definition can exist in a codebase that works with the second condition - it just tends to be limited to facades, and those facades tend to have minimal or no logic).

提交回复
热议问题