I think it's a question about the design pattern ^
^In situations where multiple classes implement a single interface,
If you need to create a new implementation in a particular class (add a new method to the interface)
How do you add new methods and how do you expand them so they don't affect other classes?
Also, it's okay if the call method is changed, but is it possible to prevent the existing call method from being changed as much as possible?
This is the sample code It's very simple~
public interface Phone {
public void call();
}
public class LG implements Phone {
@Override
public void call(){
System.out.println("calling...");
}
}
public class Apple implements Phone {
@Override
public void call(){
System.out.println("calling...");
}
}
public interface Dmb {
public List<String> channels();
}
It's a very simple code.
Let's assume that there is DMB for LG, and there is no DMB for Apple~
I need to include the function DMB in LG here, but I wonder how it works in this case.
This is an existing calling method.
Phone = new Apple();
phone.call();
Furthermore, I wonder how the method is called when LG class says that it worked as follows.
public class LG implementations Phone, Dmb {
@Override
public void call(){
System.out.println("calling...");
}
@Override
public List<String> channels(){
return new ArrayList<String>();
}
}
I think there are two questions.
The above issue is called Expression_problem.
The solution to this problem with the design pattern is to use Visitor pattern, which adds unnecessary complexity because the code must be changed to match the Visitor pattern.
A more accurate solution to the above problem is to use Type Class. Unfortunately, it is not supported in Java.
An alternative is to add the default implementation to the interface using Default method included with Java 8.
This method returns to the first problem if you want to do something other than the basic implementation.
Next question is,
There may be a way to cast and call as someone else answered above, but this is not a fundamental solution either. I used polymorphism to remove branches by type, but I had to take the branch again.
If a sub-implementation of a phone implements some more interfaces, calling the method of Dmb type
where it is already expecting Phone type
seems to be a strange implementation.
If you read the article below, I think it will help you understand and solve the problem.
Note: http://koerbitz.me/posts/Sum-Types-Visitors-and-the-Expression-Problem.html
I think almost everyone knows...
When you need DMB, you can cast it through the Dmb interface.
ArrayList<Phone>list=newArrayList<Phone>();
list.add(new LG());
list.add(new Apple());
for(Phone phone : list) {
if (phone instanceof Dmb) {
Dmb dmb = (Dmb)phone;
dmb.channels();
}
}
코드 I didn't check the code.
© 2024 OneMinuteCode. All rights reserved.