标签:turn lang pattern extend ext phone new mic 内部类
// Voltage220V.java
public class Voltage220V {
public int output220V(){
int src = 220;
System.out.println("Voltage = " + src +"V");
return src;
}
}
//Voltage5V.java
public interface Voltage5V {
public int output5V();
}
// VoltageAdapter.java
public class VoltageAdapter extends Voltage220V implements Voltage5V {
public int output5V() {
//get 220v
int srcV = output220V();
int dstV = srcV / 44;
return dstV;
}
}
// Phone.java
public class Phone {
public void charging(Voltage5V voltage5V){
if(voltage5V.output5V() == 5){
System.out.println("Ok, let‘s charge.");
}else{
System.out.println("Too high");
}
}
}
// Client.java
public class Client {
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
package adapter.objectAdapter;
public class VoltageAdapter implements Voltage5V {
private Voltage220V voltage220V;
public VoltageAdapter(Voltage220V voltage220V){
this.voltage220V = voltage220V;
}
public int output5V() {
int desV = 0;
if(voltage220V != null){
int srcV = voltage220V.output220V();
desV = srcV / 44;
}
return desV;
}
}
//Client.java
public class Client {
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220V()));
}
}
先用抽象类去默认实现接口的所有方法,使用抽象类的类只要用匿名内部类实现某一个方法即可。
//Interface4.java
public interface Interface4 {
public void m1();
public void m2();
public void m3();
public void m4();
}
// 抽象类 AbsAdapter.java
public abstract class AbsAdapter implements Interface4{
public void m1() {
}
public void m2() {
}
public void m3() {
}
public void m4() {
}
}
public class Client {
public static void main(String[] args) {
AbsAdapter absAdapter = new AbsAdapter(){
@Override
public void m1() {
System.out.println("This is m1");
}
};
absAdapter.m1();
}
}
标签:turn lang pattern extend ext phone new mic 内部类
原文地址:https://www.cnblogs.com/nedrain/p/13197946.html