06-适配者模式 [对象适配器]

 区别与类适配器的主要变化,原先接口实现类中如上图所示,具体的实现类会继承实体类,然后调用其方法,现在是将实体类电源作为参数聚合到适配器的实现中,实现了基于对象的适配器。

package com.design.adapter;

/**
 * 电源电压
 * @author Fighting
 *
 */
public class PowerVoltage {
	//电源提供220V的电压
	public int output220v(){
		int powerVolatge = 220;
		return powerVolatge;
	}
}
package com.design.adapter.inter;

/**
 * 适配器接口
 * @author Fighting
 *
 */
public interface IAdapter {
	public int output5v();
	public int output12v();
}
package com.design.adapter.inter.impl;

import com.design.adapter.PowerVoltage;
import com.design.adapter.inter.IAdapter;

/**
 * 适配器的具体实现
 * @author Fighting
 *
 */
public class ChargeAdapter implements IAdapter {

	private PowerVoltage powerVoltage;
	
	public ChargeAdapter(PowerVoltage powerVoltage) {
		this.powerVoltage = powerVoltage;
	}
	
	public void setPowerVoltage(PowerVoltage powerVoltage) {
		this.powerVoltage = powerVoltage;
	}

	@Override
	public int output5v() {
		int output220v = powerVoltage.output220v();
		int out = output220v/44;
		return out;
	}

	@Override
	public int output12v() {
		int output220v = powerVoltage.output220v();
		int out = output220v/18;
		return out;
	}

}
package com.design.user.fun;

import com.design.adapter.inter.IAdapter;

/**
 * 用户想要干什么,比如给手机充电,
 * @author Fighting
 *
 */
public class Function {
	public void chargingForPhone(IAdapter iAdapter){
		int output5v = iAdapter.output5v();
		System.out.println("我拿到了"+output5v+"的电压,可以给手机充电");
	}
	
	public void chargingForCar(IAdapter iAdapter){
		int output12v = iAdapter.output12v();
		System.out.println("我拿到了"+output12v+"的电压,可以给电动车充电");
	}
}
package com.design.adapter.client;

import com.design.adapter.PowerVoltage;
import com.design.adapter.inter.IAdapter;
import com.design.adapter.inter.impl.ChargeAdapter;
import com.design.user.fun.Function;

/**
 * 测试,模拟用户行为
 * @author Fighting
 *
 */
public class UserClient {
	static Function function = new Function();

	public static void main(String[] args) {
		PowerVoltage powerVoltage = new PowerVoltage();
		ChargeAdapter chargeAdapter = new ChargeAdapter(powerVoltage);
		chargingForPhone(chargeAdapter);
		chargingForCar(chargeAdapter);
	}
	
	private static void chargingForPhone(IAdapter iAdapter){
		System.out.println("需要给手机充电");
		function.chargingForPhone(iAdapter);
	}
	
	private static void chargingForCar(IAdapter iAdapter){
		System.out.println("需要给车充电");
		function.chargingForCar(iAdapter);
	}
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页