Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

ts Adapter pattern

/*Adapter
The Adapter design pattern is a design pattern lets you convert 
the interface of a class into another interface
that it expects.

imagine you want to turn a socket into a plug.
*/
class Socket {
  constructor(private type: string) {}

  public getType() {
    return this.type;
  }
}

// Then you make a plug class:
class Plug {
  constructor(private type: string) {}

  public getType() {
    return this.type;
  }
}

// Then you make an adapter class that will adapt 
// the socket class to the plug class:
class SocketAdapter implements Plug {
  constructor(private socket: Socket) {}

  public getType() {
    return this.socket.getType();
  }
}

//Then you make your plug:
const plug = new SocketAdapter(new Socket('Type-C'));
console.log(plug.getType());
// As you can see the adapter class uses inheritance to adapt 
// the socket class to the plug class.
Source by dev.to #
 
PREVIOUS NEXT
Tagged: #ts #Adapter #pattern
ADD COMMENT
Topic
Name
4+5 =