See the author’s blog for a detailed explanation of the “adapter pattern.

“Design patterns” part 3 structural design patterns chapter 10 adapter patterns (A: C++ implementation)

This article is a Java implementation of the “adapter pattern.”

Class adapter code implementation: target interface:

package com;

public interface Target {
	
	public void request(a);
}
Copy the code

Adaptive class:

package com;

public class Adaptee {

    public void specificRequest(a)
    {       
        System.out.println("The business code in the adapter is called!"); }}Copy the code

Class Adapter class:

package com;

public class Adapter extends Adaptee implements Target{

	public void request(a) { specificRequest(); }}Copy the code

Test code:

package com;

public class Main {

	public static void main(String[] args) {
		
	    System.out.println("Class adapter pattern test:");
	    Target target = newAdapter(); target.request(); }}Copy the code

The result is as follows:

Object adapter code implementation: target interface:

package com;

public interface Target {
	
	public void request(a);
}
Copy the code

Adaptive class:

package com;

public class Adaptee {

    public void specificRequest(a)
    {       
        System.out.println("The business code in the adapter is called!"); }}Copy the code

Class Adapter class:

package com;

public class Adapter implements Target{

    private Adaptee adaptee;
	
    public Adapter(a)
    {
        this.adaptee= new Adaptee();
    }
    
	public void request(a) { adaptee.specificRequest(); }}Copy the code

Test code:

package com;

public class Main {

	public static void main(String[] args) {
		
	    System.out.println("Class adapter pattern test:");
	    Target target = newAdapter(); target.request(); }}Copy the code

The result is as follows: