This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

Recently the computer connects wireless network signal is not very stable, network speed is very slow, think directly connect a network cable, such speed can be faster and stable point. The network cable pulls well, discovers the computer does not have the network cable crystal head (RJ45) the socket, can only net Amoy a converter. In JAVA, if we find that two classes need to call each other but are incompatible, we can create an adapter class to do the job for us, similar to the adapter for a network cable.

define

Build a bridge between incompatible interfaces. This pattern is a structural pattern that combines the functionality of these two separate interfaces

advantages

You can run any two classes that are not associated. It improves the reuse of the class and makes the use of the class more flexible and transparent.

disadvantages

Because of the single inheritance nature of JAVA, the target class must be an abstract class or interface.

The illustration

implementation

The computer

public class Computer {
    // The computer wants to connect to the Internet through the typeC interface
    public void linkInternet(RJ45ToTypeC adapter){
        // The specific implementation of the Internet, the call adapter Internet functionadapter.handleRequest(); }}Copy the code

RJ45

Public class RJ45 {public void request(){system.out.println (" Connect in RJ45, complete the network." ); }}Copy the code

RJ45ToTypeC

Adapter abstract interface

public interface RJ45ToTypeC {
    // Handle the request with the adapter <--> RJ45
    public void handleRequest(a);
}
Copy the code

Adapter

// typeC <--> Adapter <--> RJ45
public class Adapter extends RJ45 implements RJ45ToTypeC {
    @Override
    public void handleRequest(a) {
        // Connect the RJ45 connector to the Internet
        super.request(); }}Copy the code

test

public class AdapterTest {
    public static void main(String[] args) {
        Computer computer = new Computer();
        RJ45ToTypeC adapter = newAdapter(); computer.linkInternet(adapter); }}Copy the code

A printout

RJ45 connection, complete networking.Copy the code

instructions

Our computer wants to directly connect the network cable to the Internet, but the computer does not have an RJ45 socket, so we use the adapter adapter to connect one end of the network cable and the other end of the computer, playing the role of a bridge between the two, to complete the signal docking.

conclusion

When we have an incentive to modify a class in normal use, we should consider the adapter pattern, which is not added at detailed design time, but rather solves the problem of the project in service.