设计模式-适配器模式

package com.shi.design.adapter.classadapter;

//被适配者
public class Voltage220V {

	//输出220v电压
	public int outPut220V() {
		int src = 220;
		System.out.println(" 现在电压是 " + src + "V");
		return src;
	}
}
package com.shi.design.adapter.classadapter;


public interface IVoltage5V {

	public int outPut5V();
}
package com.shi.design.adapter.classadapter;

public class VoltageAdater extends Voltage220V implements IVoltage5V {

	//适配器,转换器
	@Override
	public int outPut5V() {
		System.out.println("正在进行电压转化。。。");
		int srcV = outPut220V();
		int dstV = srcV / 44;
		System.out.println(" 现在电压是 " + dstV + "V");
		return dstV;
	}

}
package com.shi.design.adapter.classadapter;

public class Phone {

	//充电
	public void changing(IVoltage5V voltage) {
		int outPut5V = voltage.outPut5V();
		if(outPut5V == 5 ) {
			System.out.println("电压是5V,可以直接输出~~~");
		}else {
			System.out.println("电压不等于5V,不可以直接输出~~~");
		}
	}
}
package com.shi.design.adapter.classadapter;

public class Test1 {

	public static void main(String[] args) {
		Phone phone = new Phone();
		phone.changing(new VoltageAdater());
	}

}

主要代码(基于上面的更改)

package com.shi.design.adapter.objectadapter;

public class VoltageAdater implements IVoltage5V {
	
	private Voltage220V voltage220V;
	
	public VoltageAdater (Voltage220V voltage220V) {
		this.voltage220V = voltage220V;
	}

	//适配器,转换器
	@Override
	public int outPut5V() {
		int dstV = 0 ;
		System.out.println("正在进行电压转化。。。");
		if(voltage220V != null) {
			int srcV = voltage220V.outPut220V();
			dstV = srcV / 44;
		}
		System.out.println(" 现在电压是 " + dstV + "V");
		return dstV;
	}

}
package com.shi.design.adapter.objectadapter;

public class Test2 {

	public static void main(String[] args) {
		Phone phone = new Phone();
		phone.changing(new VoltageAdater(new Voltage220V()));
	}

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券