methodex
methodex

Reputation: 489

Using an adapter pattern without interfaces?

I have access to a Class A, a third party concrete class that I cannot modify.

I would like to convert a similar object of class B to the third party concrete object. I'm not sure how to do it correctly

Right now I have

public class BAdapter {
   private B b;
   public BAdapter(B b) {
     this.b = b;
   }

   public A toClassA() {
      // convert to and return an instance of A
   }   
 }

It feels like this adapter class should be static, which makes it feel like more of an anti pattern.

I have a bunch of classes from the third party that I am going to need to convert and would like to know of the proper pattern I should be using. The third party does not provide any interfaces, just concrete classes, so I cannot use the true adapter pattern. Any options or ideas?

Upvotes: 1

Views: 890

Answers (1)

velis
velis

Reputation: 10025

The way I see it, you have three options:

  1. If your only need is conversion from B to A, you don't need the adapter. Just add the toClassA() method to class B.
  2. Use the adapter if you want to map class A interface to mimic that of class B so that you actually instantiate only the adapter (and implicitly A) when you need A functionality.
  3. If B adds functionality to A, derive B from A: classic inheritance or even multiple inheritance if you need interface compatibility to a class C that we don't know of.

Upvotes: 1

Related Questions