您的位置:首页 > 其它

设计模式——适配器模式

2016-07-26 16:46 246 查看
适配器模式有两种:

类的适配器:



//需要被适配的类
public class Adaptee{
public void printAdaptee(){
System.ou.println("适配器的类");
}
}

//目标接口
public interface Target{
void printtarget();
}

//适配器
public class Adapter extends Adaptee implements Target{
public void printtarget(){
super.printAdaptee();
}
}

//测试
public sattic void main(String[] args){
Target target=new Adapter();
target.printtarget();
}
/*
这样通过继承和实现接口的形式就将原来的Adaptee里的printAdaptee(),方法实现到 Target里
*/


对象的适配器:

使用的是关联的关系。



//需要被适配的类
public class Adaptee{
public void printAdaptee(){
System.ou.println("适配器的类");
}
}

//目标接口
public interface Target{
void printtarget();
}

//适配器
public class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee=adaptee;
}
public void printtarget(){
adaptee.printAdaptee();
}
}

//测试
public sattic void main(String[] args){
Target target=new Adapter(new Adaptee());
target.printtarget();
}
/*
这样通过继承和关联的形式就将原来的Adaptee里的printAdaptee(),方法实现到 Target里
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式