In this article, we will learn how to use and implement the Adapter Pattern in TypeScript with an example.
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
TypeScript Abstract Factory Pattern Example
Let's create abstractFactory.ts file and add the following code to it:
export class Adaptee {
public method(): void {
console.log("`method` of Adaptee is being called");
}
}
export interface Target {
call(): void;
}
export class Adapter implements Target {
public call(): void {
console.log("Adapter's `call` method is being called");
var adaptee: Adaptee = new Adaptee();
adaptee.method();
}
}
Usage
Let's create demo.ts file and add the following code to it:
import { Adapter } from "./adapter";
export function show() : void {
var adapter: Adapter = new Adapter();
adapter.call();
}
show();
Run:
- Compile the above code using the TypeScript compiler.
- Above code is compiled to plan JavaScript code
- Run Javascript code using node
PS C:\Users\RAMESH\design_patterns_in_typescript\adapter> tsc --target ES5 .\demo.ts
PS C:\Users\RAMESH\design_patterns_in_typescript\adapter> node .\demo.js
Adapter's `call` method is being call
Check out how to install TypeScript compiler and run TypeScript file in VS Code at https://www.javaguides.net/2019/09/install-typescript-compiler-and-run-code.html
All TypeScript Design Patterns
1. Creational Design Patterns
Creational patterns provide various object creation mechanisms, which increase flexibility and reuse of existing code.
- TypeScript Singleton Pattern Example
- TypeScript Factory Design Pattern with Example
- TypeScript Abstract Factory Pattern Example
- TypeScript Builder Pattern Example
- TypeScript Prototype Pattern Example
2. Structural Design Patterns
Structural patterns explain how to assemble objects and classes into larger structures while keeping these structures flexible and efficient.
- TypeScript Bridge Pattern Example
- TypeScript Adapter Pattern Example
- TypeScript Decorator Pattern Example
- TypeScript Composite Pattern Example
- TypeScript Flyweight Design Pattern Example
- TypeScript Facade Pattern Example
- TypeScript Proxy Pattern Example
3. Behavioral Design Patterns
Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects.
- TypeScript Command Pattern Example
- TypeScript Chain of Responsibility Pattern Example
- TypeScript Visitor Pattern Example
- TypeScript Template Method Pattern Example
- TypeScript Strategy Pattern Example
- TypeScript State Pattern Example
- TypeScript Observer Pattern Example
- TypeScript Memento Pattern Example
- TypeScript Mediator Pattern Example
- TypeScript Iterator Pattern Example
- TypeScript Interpreter Design Pattern Example