Adapter Pattern

Adapter pattern is to create a wrapper class to convert the type to the correct type. For example:

package designpatterns.adapter;

public interface Entity {
}

package designpatterns.adapter;


import java.util.ArrayList;
import java.util.List;

public class Database {
  public final List<Entity> entities;

  public Database() {
    entities = new ArrayList<>();
  }
}

In here entities only accept Entity, what happen if we want to store User

package designpatterns.adapter;

public class User {
  public final String userName;

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

We can then create an Adaptor that would be able to convert from Entity to User

package designpatterns.adapter;

public class UserEntityAdapter implements Entity {
  private User user;
  
  public UserEntityAdapter(User user) {
    this.user = user;
  }

  @Override
  public String toString() {
    return this.user.userName;
  }
}

package designpatterns.adapter.test;

import designpatterns.adapter.Database;
import designpatterns.adapter.User;
import designpatterns.adapter.UserEntityAdapter;
import org.junit.jupiter.api.Test;

public class DatabaseTest {
  @Test
  void endToEnd_givenDatabase_addUser() {
    Database database = new Database();

    User user = new User("austin");
    database.entities.add(new UserEntityAdapter(user));

    System.out.println(database.entities);
  }
}