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);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值