Adapter Design Patterns

What is adapter mode?

Converting the interface of one class into another interface that the client desires, the Adapter pattern enables classes to work together that would otherwise not work together due to incompatible interfaces.

Roles in the pattern:

Target interface (target): The interface expected by the client. Targets can be concrete or abstract classes, or interfaces.

The class that needs to be adapted (Adaptee): The class or adapter class that needs to be adapted.

Adapter: Convert the original interface to the target interface by wrapping an object that needs to be adapted


Class Diagram:



Take keyboard and pc operation as an example

Create an adapter interface:

package com.gcxzflgl.adapter;

public interface Target {
	void handleReq();
}

Create the adapted class

package com.gcxzflgl.adapter;

/**
 * the adapted class
 * (equivalent to the example, PS/2 keyboard)
 * @author Administrator
 *
 */
public class Adaptee {
	
	public void request(){
		System.out.println("Can complete the required function requested by the customer!");
	}
}

Create the adapter:

package com.gcxzflgl.adapter;

/**
 * Adapter (object adapter method, which uses a combination method to integrate with the adapted object)
 * (equivalent to usb and ps/2 adapter)
 * @author Administrator
 *
 */
public class Adapter2  implements Target {
	
	private Adaptee adaptee;
	
	@Override
	public void handleReq() {
		adaptee.request();
	}

	public Adapter2(Adaptee adaptee) {
		super();
		this.adaptee = adaptee;
	}
	
	
	
}

Simulate the client to call:

package com.gcxzflgl.adapter;

/**
 * client class
 * (equivalent to the laptop in the example, only USB port)
 * @author Administrator
 *
 */
public class Client {
	
	public void test1(Target t){
		t.handleReq();
	}
	
	public static void main(String[] args) {
		Client  c = new Client();
		Adaptee a = new Adaptee();
		Target t = new Adapter2(a);
		c.test1(t);
		
	}
	
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324726027&siteId=291194637