适配器模式将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间
类适配器
要加入进来的类
package com.zw.mymaven;
//要加入进来的类
public class Adaptee {
public void Adapteemethod() {
System.out.println("我想要加入进来");
}
}
通用接口
package com.zw.mymaven;
public interface Common {
public void Commonmethod();
}
通用接口实现类
package com.zw.mymaven;
public class Commonimp implements Common {
public void Commonmethod() {
System.out.println("我是标准!");
}
}
适配器
package com.zw.mymaven;
public class Adapt extends Adaptee implements Common {
public void Commonmethod() {
super.Adapteemethod();
}
}
测试类
package com.zw.mymaven;
public class TestAdapt {
public static void main(String[] args) {
Common common = new Commonimp();
common.Commonmethod();
Common common2 = new Adapt();
common2.Commonmethod();
}
}
对象适配器
要加入进来的类、通用接口、通用接口都不用变
适配器
package com.zw.mymaven;
public class Adapt implements Common {
private Adaptee adaptee;
public Adapt(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void Commonmethod() {
this.adaptee.Adapteemethod();
}
}
测试类
package com.zw.mymaven;
public class TestAdapt {
public static void main(String[] args) {
Common common = new Commonimp();
common.Commonmethod();
Common common2 = new Adapt(new Adaptee());
common2.Commonmethod();
}
}