- Published on
[Structural] Adapter
- Authors
- Name
- Khánh
Problems
- How to use an old layer code for a new layer without effect to the old code?
Adapter pattern
- Create an adapter to connect an old layer to use in the new context.
Steps:
- Determine an old layer
- Create a new layer with input is an old instance
- Using the new layer in new context.
Example:
- Old layer
class OldSystem {
oldRequest() {
return "Old system request";
}
}
- New layer
interface Target {
request(): string;
}
class SystemAdapter implements Target {
constructor(private oldSystem: OldSystem) {}
request(): string {
return this.oldSystem.oldRequest();
}
}
- Implementation of the new layer
const oldSystem = new OldSystem();
console.log(oldSystem.oldRequest()); // Old system request
const newSystem = new SystemAdapter(oldSystem);
console.log(newSystem.request()); // Old system request
Conclusions
- Keep the old layer (no need to modify it)
- Easier to expand the old layer
- Can reuse code