Multiple Interfaces extending in Java

2019-04-16 07:11发布

I need to implement a Facade design pattern with multiple inheritance of interfaces in Java or to be correct Facade with Bridge design pattern. I know this is possible because I saw it in as a part of one system, but I don't remember the implementation very well.
Here is my implementation so far:

public interface IOne {
public void methodOneIOne();
public void methodTwoIOne();
}

And its implementation:

public class One implements IOne {
@Override
public void methodOneIOne() {
    System.out.println("methodOneIOne()");
}
@Override
public void methodTwoIOne() {
    System.out.println("methodTwoIOne()");
}  }


public interface ITwo {
public void methodOneITwo();
public void methodTwoITwo();
}
public class Two implements ITwo {
@Override
public void methodOneITwo() {
    System.out.println("methodOneITwo()");
}
@Override
public void methodTwoITwo() {
    System.out.println("methodTwoITwo()");
}}

And the facade:

public interface IFacade extends IOne, ITwo {}

So, from here I don't know where to go. If I create a class that implements IFacade, then it will be required to implement all of the methods, and this isn't what I want.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-16 07:15

If I create class that implements IFacade, then if will require to implement all of the methods, and this isn't what I want.

Why not? What do you want Facade to do?

An implementation of Facade, as written, would have to implement all the methods, but that need not mean repeating all the code you've written for One and Two. Just use composition:

public class Facade implements IFacade
{
    private IOne one;
    private ITwo two;

    public Facade(IOne one, ITwo two)
    {
        this.one = one; 
        this.two = two;    
    }

    @Override
    public void methodOneIOne() 
    {
        this.one.methodOneInOne(); 
    }

    // You see the point, I hope.

}

This design has the added benefit of allowing you to change the implementations of your Facade at will: just substitute different implementations of each interface. These can be dynamically generated proxies or anything else that you can dream up. That's the beauty of designing to an interface.

查看更多
▲ chillily
3楼-- · 2019-04-16 07:33

What are you actually trying to do with your facade class? If you are just trying to pass through most methods, possibly modifying a few then a dynamic proxy might be what you want.

Otherwise you would in fact have to implement all methods of IFacade, as Java does not allow you to use multiple inheritance, so you could not extend both One and Two.

查看更多
登录 后发表回答