Question

I have one query regarding Adapter pattern, how to implement in this scenario. I have one interface which return type is single object.

public interface MyInt {
MyObj read();
}

However, my adaptee implementation class say, MyAdaptee has method which return list of MyObj object.

public class MyAdaptee {
public MyObj[] readTheInput() {
// implementation here
}

Now, how can i write adapter here on top of MyAdaptee? since I can't change the interface, how can i send multiple object of MyObj to client which expect single object?

PS: MyObj is also interface.

Was it helpful?

Solution

You need to implement Adapter using its semantics, and hence, may have to modify the Adaptee implementation such that it returns array items one by one by keeping track of what it has returned earlier.

Below is indicative implementation, I have not compiled or tested it, so take it for logic it represents.

public class MyAdaptee implements MyInt {
     private MyObj[] buffer = new MyObj[0];
     private indexOfLastBufferedItemReturned = 0;

  @Override
  public MyObj read() {
     if (indexOfLastBufferedItemReturned >= buffer.length) {
        buffer = readTheInput(); //use existing implementation here
        indexOfLastBufferedItemReturned = 0;
     }
     return buffer[indexOfLastBufferedItemReturned++];   
  }

  public MyObj[] readTheInput() {    
     // implementation here   
  }   

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top