[Java] [Java] Adapter pattern

1 minute read

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code for verification

For example, let’s say you have the following Oimo class. This class gives you a taste.

Oimo.java


package adapter;

public class Oimo {
public String feelTaste() {
return "delicious";
}
}

However, because I want information on potatoes when I eat them, Declare as follows. The NewAbility class and NewOimo class that appear here are the main characters of the Adapter pattern.

User.java


package adapter;

public class User {
public static void main(String[] args) {
NewAbility oimo = new NewOimo("Red Azuma");
System.out.println(oimo.oimoInfo());
}
}

First, let’s create a NewOimo class that inherits the Oimo class. Accompany them with new abilities so that you can obtain potato information.

NewOimo.java


package adapter;

public class NewOimo extends Oimo implements NewAbility {

public final String name;

public NewOimo(String name) {
this.name = name;
}

@Override
public String oimoInfo() {
return getName() + feelTaste();
}

private String getName() {
return this.name;
}
}

Next, let’s create the NewAbility interface that will be the bridge between the User class and the NewOimo class, and delegate it to the NewOimo class.

NewAbility.java


package adapter;

public interface NewAbility {
public String oimoInfo();
}

Class diagram

Adapter class diagram.png

Impression

If you want to use the existing code but cannot use it directly because the IF is different, this Adapter pattern will be useful. Remember! Is it not used for new development?

See you again (^_^)