Design Patterns Handbook
  • Introduction
  • Creational Patterns
    • Builder
    • Factory
    • Abstract Factory
    • Factory Method
    • Prototype
    • Singleton
    • Object Pool
    • Revealing Constructor
  • Structural Patterns
    • Adapter
    • Composite
    • Proxy
    • Flyweight
    • Facade
    • Bridge
    • Decorator
    • Private Class Data
  • Behavioral Patterns
    • Template Method
    • Mediator
    • Chain Of Responsibility
    • Observer
    • Strategy
    • Command
    • State
    • Visitor
    • Memento
    • Interpreter
    • Null Object
    • Iterator
    • Middleware
  • Clean Code Patterns
    • Extract Method
    • Clarify Responsibility
    • Remove Duplications
    • Keep Refactoring
    • Always Unit Test
    • Create Data Type
    • Comment to Better Name
    • Consistent Naming
    • If-else over ternary operator
    • Composition over Inheritance
    • Too Many Returns
    • Private to Interface
  • Anti Patterns
    • Big Ball of Mud
    • Singleton
    • Mad Scientist
    • Spaghetti Code
    • It Will Never Happen
    • Error Codes
    • Commented Code
    • Abbreviations
    • Prefixes
    • Over Patternized
    • Generic Interface over Function
Powered by GitBook
On this page

Was this helpful?

  1. Structural Patterns

Adapter

Adapter lets classes work together that could not otherwise because of incompatible interfaces.

Example - User adaptation

Lets say we work for eBay company and there are other users we need to integrate with our systems. Our, eBay, user is defined by EbayUser interface. External users are represented by class ExternalUser, but we do not want to mess with this class in our code and that is why we create an adapter that will adapt external user into our system.

interface EbayUser {
    String getUserName();
}

class EbayUserImpl implements EbayUser {

    private String userName;

    public EbayUserImpl(String userName) {
        this.userName = userName;
    }

    @Override
    public String getUserName() {
        return userName;
    }
}

class ExternalUserToEbayUserAdapter implements EbayUser {

    private String userName;

    public ExternalUserToEbayUserAdapter(ExternalUser payPalUser) {
        userName = payPalUser.getUsername();
    }

    @Override
    public String getUserName() {
        return userName;
    }
}

class ExternalUser {

    private String username;

    public ExternalUser(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }
}

Here is an example how we could adapt an external user into our system.

ExternalUser externalUser = new ExternalUser("john");

EbayUser ebayUser = new ExternalUserToEbayUserAdapter(externalUser);
PreviousStructural PatternsNextComposite

Last updated 5 years ago

Was this helpful?