Answer the question
In order to leave comments, you need to log in
Did I understand the principle of dependency inversion correctly?
There is an interface
public interface INumberOperation {
public void executeOperation (int number);
}
public class NumberOperation1 implements INumberOperation{
@Override
public void executeOperation(int number) {
number += number * 2;
System.out.println(number);
}
}
public class NumberOperation2 implements INumberOperation{
@Override
public void executeOperation(int number) {
number += 100;
System.out.println(number);
}
}
public class Main {
public static void main(String[] args) {
INumberOperation iNumberOperation;
iNumberOperation = new NumberOperation1();
iNumberOperation.executeOperation(100);
iNumberOperation = new NumberOperation2();
iNumberOperation.executeOperation(100);
}
}
Answer the question
In order to leave comments, you need to log in
The main idea behind the Dependency Inversion Principle is "Details depend on abstractions, but not abstractions depend on details".
In your example, the Main class depends on everything: the INumberOperation interface and both the NumberOperation1, NumberOperation2 classes. That is, the principle of dependency inversion does not work here at all. No way.
It appears in the following example. Let me have some abstract logic "read a number, perform an operation on it, write down the result". This abstract logic (that's why it is abstract) should not know anything from where it reads the number, what operation it performs on it, or where and how it writes the result. Thus, we have a module consisting of
interface NumberInput {
int read();
}
interface NumberProcessor {
int process(int a);
}
interface NumberOutput {
void write(int a);
}
class Processor {
private final NumberInput input;
private final NumberProcessor processor;
private final NumberOutput output;
public Processor(NumberInput input, NumberProcessor processor, NumberOutput output) {
this.input = input;
this.processor = processor;
this.output = output;
}
void process() {
output.write(processor.process(input.read()));
}
}
Watch Alexander Byndyu's video at this link: https://blog.byndyu.ru/2013/06/blog-post_27.html (This is C#, but in general it is very similar to Java, so it should be perceived normally) He expands the example there very well. After watching this video, you start to look at the code in a new way.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question