Adapter Pattern
Posted nedrain
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Adapter Pattern相关的知识,希望对你有一定的参考价值。
Adapter
An Example
// 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());
}
}
Attention
对象适配器
新的 VoltageAdapter.java 聚合关系
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();
}
}
抽象方法不能实例化,但是可以通过匿名内部类的方式使用。
以上是关于Adapter Pattern的主要内容,如果未能解决你的问题,请参考以下文章
为啥 recyclerview$adapter 在片段中为空
设计模式完结--适配器模式(adapter pattern)
[Design Pattern] Adapter Design Pattern