define

By transforming the interface of one class into another interface that the customer expects, adapters enable classes whose interfaces are incompatible with each other to cooperate.

How to use

Adapter pattern also come from our life, such as mobile phone power adapter, laptop/same Pad and so on all need the power adapter, reason is the electronic equipment are in need of power supply interface is not a 220 v, is the need to use for switching adapter (5 v, etc.), the corresponding code is what? (adapter pattern how to fall to the ground)?

First, there is a 220V power supply interface and implementation

public interface V220Power {
    / * * * *@returnSupply voltage */
    int getPower(a);
}
Copy the code
public class V220PowerImpl implements V220Power {
    @Override
    public int getPower(a) {
        return 220; }}Copy the code

Now you need a 5V power port to charge your iPhone

public interface V5Power {
    int getPower(a);
}
Copy the code

Implement a 5V power adapter to convert 220V to 5V

public class V5PowerAdapter implements V5Power {

    private V220Power v220Power;

    public V5PowerAdapter(V220Power v220Power) {
        this.v220Power = v220Power;
    }

    @Override
    public int getPower(a) {
        int power = this.v220Power.getPower();
        // Convert 220V to 5V after complex processing
        power = 5;
        returnpower; }}Copy the code

conclusion

So far, I have successfully adapted the 220V power supply to the 5V voltage and charged my iPhone. An adapter converts an existing interface into a new interface that meets the requirements and can use the results of the existing interface at the same time, reducing the cost of modification and enhancing scalability.