开发者

Java pattern to change API interface name?

Is there some sort of pattern/solution I can use to achieve the following:

I am using an API that has an interface called ApiInterface.

The interface has 1 method: void apiMethod(BaseType val);.

Now, I want to use this functionality but I want to use my own interface, a different method name, and a subtype of BaseType:

interface MyInterface {
  void myMethod(MyType val); 
}

MyType extends BaseType. myMethod should just invoke apiMethod, the only difference is that it us开发者_JAVA百科es MyType.

Is there a way to create MyInterface such that its just a pass through to ApiInterface but using a different method name and my own extension of BaseType? I managed to do this using an abstract class that extends ApiInterface, but I want to use an interface, not a class.


You can try Adaptor Design Pattern. It will help you.


First, an interface does not implement anything. So your ApiInterface should have defined:

   void apiMethod(BaseType val);

and either there should be some concrete class that implements this method or you have to implement it yourself.

But apart from that, you may need an Adapter.

public interface ApiAdapter{
    void myMethod(MyType val);
}

public class ConcreteAdapter implements ApiAdapter{
     void myMethod(MyType val){
         ApiInterface api = new ConcreteApiClass();
         api.apiMethod(val);//should work since MyType extends BaseType
     }
}

Now in your code you can declare ConcreteAdapter objects and invoke myMethod using MyType without any reference to ApiInterface etc.


How about something like this:

public class ApiAdapter implements MyInterface {
  private final ApiInterface delegate;

  public ApiAdapter(ApiInterface delegate) {
    this.delegate = delegate;
  }

  public void myMethod(MyType value) {
    delegate.apiMethod(value);
  }
}

Now if you have code that has a reference to an ApiInterface instance and you want to convert that to a MyInterface instance you can do something like this:

ApiInterface instance = ...;
MyInterface adaptedInstance = new ApiAdapter(instance);

Now you can hand off adaptedInstance to anyone who needs a MyInterface

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜