适配器模式:
1,类适配器模式
源角色(Adaptee):
package com.classadpter;
public class Adaptee {
public void code(){
System.out.println("能写代码");
}
}
目标抽象角色(Target):
package com.classadpter;
public interface Target {
public void code();
public void pm();
}
适配器角色(Adapter)
package com.classadpter;
//Adpter:就是继承Target,继承Adaptee
public class Adapter extends Adaptee implements Target {
//这里这个IT民工即能写代码,也想能做产品,话说好多coder都喜欢这么yy来着
@Override
public void pm() {
// TODO Auto-generated method stub
System.out.println("还能做产品");
}
public void work(){
this.code();
this.pm();
}
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.work();
}
}
test result:
能写代码
还能做产品
2,对象适配器模式
源角色(Adaptee):
package com.objectadapter;
public class Adaptee {
public void code(){
System.out.println("能写代码");
}
}
目标抽象角色(Target):
package com.objectadapter;
public interface Target {
public void code();
public void pm();
}
package com.objectadapter;
//Adpter:就是继承Target,继承Adaptee
public class Adapter implements Target {
public Adaptee adaptee ;
//这里这个IT民工即能写代码,也能做产品,话说好多coder都喜欢这么yy来着
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
public void code() {
// TODO Auto-generated method stub
this.adaptee.code();
}
public void pm() {
System.out.println("我还能做产品");
}
public void work(){
this.code();
this.pm();
}
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Adapter adapter = new Adapter(adaptee);
adapter.work();
}
}
适配器模式解析
本文详细介绍了适配器模式的两种实现方式:类适配器模式和对象适配器模式。通过具体示例代码展示了如何将不兼容接口的类转换为客户端期望的接口。

1331

被折叠的 条评论
为什么被折叠?



