经典结构:

适配器模式Adapter-经典结构-JAVA实现

JAVA UML类图:

适配器模式Adapter-经典结构-JAVA实现

实现源码及说明:

Client.java

package com.pattern.adapter;
/*
 * 客户端类(手机)
 * main逻辑中处理:手机-》miniUSB接口-》miniUSB与USB适配器-》USB5v电源输入,获取电量
 * 其中分为类适配器与对象适配器
 * @author yuanwm
 *
 */
public class Client {
	public void DoRequest(Target ObTarget) {
		ObTarget.Request();
	}
	public static void main(String[] args) {
		Client computerClient = new Client();

		//类适配器
		AdapterClass pspToUsbClassAdapter = new AdapterClass();
		System.out.println("类适配充电:");
		computerClient.DoRequest(pspToUsbClassAdapter);
		
		Adaptee pspKeyboardAdaptee = new Adaptee();
		//对象配器
		System.out.println("类适配充电:");
		AdapterObject pspToUsbObjectAdapter = new AdapterObject(pspKeyboardAdaptee);
		
		computerClient.DoRequest(pspToUsbObjectAdapter);
	}
}

Adaptee.java

package com.pattern.adapter;
/*
 * 被适配的类(USB5v电源输入)
 * @author yuanwm
 *
 */
public class Adaptee {
	public void SpecificRequest() {
		System.out.println("USB5v电源输入");
	}
}

AdapterClass.java 

package com.pattern.adapter;
/*
 * 类适配器实现(miniUSB与USB适配器)
 * @author yuanwm
 *
 */

public class AdapterClass extends Adaptee implements Target{
/*
 * 类适配器-通过继承的方式
 * Java为单继承,因此一个类的继承机会只有一次;因此,不建议使用这种方式。
 */
	@Override
	public void Request() {
		// TODO Auto-generated method stub
		super.SpecificRequest();
	}

}

AdapterObject.java 

package com.pattern.adapter;
/*
 * 对象适配器实现(miniUSB与USB适配器)
 * @author yuanwm
 *
 */

public class AdapterObject implements Target{
/**
* 对象适配器,通过对象组合的方式
*/
	private Adaptee objectAdaptee;
	
	public AdapterObject(Adaptee inAdaptee) {
		super();
		this.objectAdaptee = inAdaptee;
	}
	
	@Override
	public void Request() {
		// TODO Auto-generated method stub
		objectAdaptee.SpecificRequest();
	}


}

Target.java

package com.pattern.adapter;
/*
 * 需要适配的接口(miniUSB接口)
 * @author yuanwm
 *
 */
public interface Target {
	public void Request();
}

 

 

 

相关文章:

  • 2022-12-23
  • 2021-11-19
  • 2021-09-26
  • 2021-09-22
  • 2021-11-15
  • 2021-06-17
  • 2022-12-23
  • 2021-05-04
猜你喜欢
  • 2021-07-02
  • 2022-12-23
  • 2021-10-13
  • 2021-11-11
  • 2021-09-21
  • 2021-05-21
  • 2022-02-13
相关资源
相似解决方案