(example code in PHP, but this can apply to more languages)
I have a scenario with an adapter pattern, where I have classes, interfaces and objects with different roles, like so:
- An original object implementing
CatInterface
. - A class that implements
DogInterface
, which wraps aCatInterface
object. - An instance of that class, wrapping the
$cat
object. - A service object, that wraps cat objects into new adapter instances.
My question: In this scenario, which component is the "adapter"?
E.g. the service object might look like this:
class CatDogAdapter {
function adapt(CatInterface $cat) : DogInterface {
return new DogFromCat($cat);
}
}
$adapter = new CatDogAdapter();
$cat = new Cat;
$dog = $adapter->adapt($cat);
In this example, I used the term "adapter" in the name of the service object / class. But is this the common way that the name is used? Or should I rather use the term "adapter" for the "DogFromCat" class, and name the service e.g. "AdapterFinder" or "AdapterFactory"?
Ideal would be literature or examples that point to a common practice in naming these components.
Maybe such a consensus does not exist, and it is all the wild west - in this case the question goes nowhere, and I have to decide for myself.
I am tagging this as PHP and Java, because I think the question would apply to both languages.
EDIT: Why have an adapter factory?
The answer I got so far suggests that the example might be too trivial.
My actual use case is something like this:
// Maybe $adapter should rather be named $adapterFactory?
$dogFromCat = $adapter->adapt($cat, DogInterface::class);
There is some mapping logic that determines which adapter class to use depending on the desired return type and the type of the to-be-adapted object.
But even with the simpler example that only builds DogFromCat objects, there can be reasons to have such an adapter factory object:
- It can be passed around as a dependency to other components.
- It can contain dependencies to be injected into the DogFromCat in addition to the $cat object.
- It can behave differently for different sub-types of cat.
As the text of this edit suggests, the best way to name this might be "AdapterFactory". So maybe I answered my question myself this way.