Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Structural design patterns

Adapter

Adapter works as a bridge between two incompatible interfaces.

  • Adapter pattern involves a single class as adaptor which is responsible for communication between two independent or incompatible interfaces.

  • It helps two incompatible interfaces to work together.

  • Most frequently used in JavaScript.

EX:
// client form object
interface PersonClient {
    firstName: string;
    lastName: string;
    phNumber: string;
    age: string;
    city: string;
    address: string;
};

// server [FormBody]
interface PersonServer {
    Name: {
        firstName: string;
        lastName: string;
    },
    OtherDetails: {
        phNumber: string;
        age: string;
        city: string;
        address: string;
    }
}

class PersonAdapter {
    constructor() {}
    processServerData(personServer: PersonServer):PersonClient {
        return {
            firstName: personServer.firstName,
            lastName: personServer.lastName,
            phNumber: personServer.phNumber,
            age: personServer.age,
            city: personServer.city,
            address: personServer.address
        };
    }
    processClientData(personClient: PersonClient): PersonServer {
        return {
            Name: {
                firstName: personClient.firstName,
                lastName: personClient.lastName
            },
            OtherDetails: {
                phNumber: personClient.phNumber,
                age: personClient.age,
                city: personClient.city,
                address: personClient.address
            }
        };
    }
}
const personAdapter = new PersonAdapter();
let clientResponse: PersonClient = {};
fetch('url', { method: 'POST',
               body: personAdapter.processClientData(personClient)
              })
  .then((personServer: PersonServer) => {
    clientResponse = personAdapter.processServerData(personServer);
});

Explanation for Example:

Client form data is in a flat key-value pair object but the server form body is in grouper objects.

Adopter will convert the client object structure to server form body structure and vice versa

PreviousStructural design patternsNextBridge

Last updated 5 years ago

Was this helpful?