Programing

5 살짜리에게 의존성 주입을 설명하는 방법?

lottogame 2020. 5. 1. 07:57
반응형

5 살짜리에게 의존성 주입을 설명하는 방법? [닫은]


의존성 주입 을 설명하는 좋은 방법은 무엇입니까 ?

Google에서 여러 자습서를 찾았지만 독자가 Java 초보자라고 생각하는 자습서는 없습니다. 이것을 초보자에게 어떻게 설명 하시겠습니까?


다섯 살짜리 아이에게 의존성 주입을하겠습니다.

냉장고에 물건을 가져 가면 문제가 발생할 수 있습니다. 당신은 문을 열어두고, 엄마 나 아빠가 원하지 않는 것을 얻을 수 있습니다. 우리가 가지고 있지 않거나 만료 된 것을 찾고있을 수도 있습니다.

당신이해야 할 일은 "나는 점심으로 마실 음식이 필요하다"는 말을해야한다는 것입니다. 그리고 우리는 당신이 앉아 식사를 할 때 무언가를 갖도록 할 것입니다.


이건 어때?

수업 Employee이 있고이 직원이있는 경우 다음과 같이 수업을 정의 Address할 수 있습니다 Employee.

class Employee {
    private Address address;

    // constructor 
    public Employee( Address newAddress ) {
        this.address = newAddress;
    }

    public Address getAddress() {
    return this.address;
    }
    public void setAddress( Address newAddress ) {
        this.address = newAddress;
    }
}

지금까지 모든 것이 잘 보입니다.

이 코드는 직원과 주소 간의 HAS-A 관계를 보여줍니다 .

이제이 HAS-A 관계는 그들 사이에 종속성을 만들었습니다. 문제는 생성자 안에 있습니다.

Employee인스턴스 를 만들 때마다 인스턴스가 필요 Address합니다.

 Address someAddress = ....
 Employee oscar = new Employee( someAddress ); 

이 방법으로 작업하면 특히 단위 테스트를 수행하려는 경우 문제가 됩니다.

당신은 하나의 특정 오브젝트를 테스트 할 때 가장 큰 문제가되어, 다른 객체의 인스턴스를 생성해야하고, 가장 가능성이 아직의 인스턴스를 만들 필요가 다른 것을 할 개체를. 체인을 관리하기 어려워 질 수 있습니다.

이를 피하기 위해 다음과 같이 생성자를 변경할 수 있습니다.

  public Employee(){
  }

인수 없음 생성자를 사용합니다.

그런 다음 원하는 때에 주소를 설정할 수 있습니다.

 Address someAddress = ....
 Employee oscar = new Employee();
 oscar.setAddress( someAddress ); 

여러 속성이 있거나 오브젝트를 작성하기 어려운 경우, 이는 드래그 일 수 있습니다.

그러나 이것에 대해 생각해보십시오. Department속성 을 추가하십시오 .

  class Employee {
      private Address address;
      private Department department;

  ....

If you have 300 employees, and all of them need to have the same department, and plus that same department has to be shared between some other objects ( like the company list of departments, or the roles each department have etc ) then you'll have a hard time with the visibility of the Department object and to share it through all the network of objects.

What the Dependency Injection is all about it to help you to, well, "inject" these dependencies in your code. Most of the frameworks allow you to do this by specifying in an external file, what object is to be injected.

Assume a properties file for a fictitious dependency injector:

  #mock employee
  employee.address = MockAddress.class
  employee.department = MockDepartment.class

  #production setup 
  employee.address = RealAddress.class
  employee.department = RealDepartment.class

You'll define what to inject for a given scenario.

What the Dependency Injector framework will do is to set the correct objects for you, so you don't have to code setAddress or setDepartment. This would be done either by reflection or by code generation or other techniques.

So, the next time you need to test the Employee class you may inject mock Address and Departments objects without having to code all the set/get for all your test. Even better, you can inject real Address and Department objects in production code, and still have the confidence your code works as tested.

That's pretty much about it.

Still I don't think this explanation is suitable for a 5 yr old as you requested.

I hope you still find it useful.


When writing a class, it's natural for it to make use of other objects. You may have a database connection, for example, or some other service that you use. These other objects (or services) are dependencies. The simplest way to write the code is simply to create and use those other objects. But this means your object has an inflexible relationship to those dependencies: no matter why you are invoking your object, it uses the same dependencies.

A more powerful technique is to be able to create your object and provide it with dependencies to use. So you might create a database connection to use, then hand it to your object. This way, you can create your object with different dependencies at different times, making your object more flexible. This is dependency injection, where you "inject" the dependencies into the object.

BTW: In the modern presentation style of using flickr photos to illustrate concepts, this could be illustrated with an addict shooting themselves up with drugs. Oh, wait, that's injection dependency... OK, sorry, bad joke.


I don't know of any simplified tutorials, but I can give you an almost 25 250-words-or-less version:

With dependency injection an object doesn't configure its own components based on things it already knows, rather the object is configured by higher level logic, and then it calls components that it didn't have built-in foreknowledge of. The idea is to make the object more of a component and less of an application, relocating configuration tasks at a higher level. This makes the object more likely to be useful in the future or with a different configuration.

It's better for testing, it's better when it comes time to revise the application. A typical implementation puts the configuration in XML and uses a framework to dynamically load classes.


When you get given a new Nintendo, you can just use the buttons and touch screen to play games.

But at the Nintendo factory, they need to know how to put one together.

When the smart people at the factory bring out a Nintendo DS, it will be different inside, but you will still know how to use it.

참고URL : https://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old

반응형