23种设计模式学习之适配器模式
一.类的适配器模式
需要适配的类
public class Source {
public void method1(){
System.out.println("method1");
}
}
适配的接口
public interface Targetable {
void method1();
void method2();
}
适配器
public class Adapter extends Source implements Targetable {
@Override
public void method2() {
System.out.println("method2");
}
}
实例,这样Targetable接口的实现类就具有了Source类的功能。
public class Demo {
public static void main(String[] args) {
Targetable targetable=new Adapter();
targetable.method1();
targetable.method2();
}
}
二.对象的适配器模式
对象的适配不在继承目标类,将目标类当做适配类构造函数的入参,
public class Adapter implements Targetable {
private Source source;
public Adapter(Source source){
this.source=source;
}
@Override
public void method1() {
source.method1();
}
@Override
public void method2() {
System.out.println("method2");
}
}
实例
public class Demo {
public static void main(String[] args) {
Source source=new Source();
Targetable targetable=new Adapter(source);
targetable.method1();
targetable.method2();
}
}
三.接口的适配器模式
当一个接口有很多方法,实现类中需要实现所有的方法,有很多方法是我们不关心的,这时需要用到适配器模式
方法很多的接口
public interface Source {
void method1();
void method2();
}
抽象的实现
public abstract class Wrapper implements Source{
@Override
public void method1() {
}
@Override
public void method2() {
}
}
只重新方法一
public class SourceWrapperMethod1 extends Wrapper {
@Override
public void method1(){
System.out.println("");
}
}
只重新方法二
public class SourceWrapperMethod2 extends Wrapper {
@Override
public void method2(){
System.out.println("");
}
}
实例应用
public class Demo {
public static void main(String[] args) {
Wrapper wrapper=new SourceWrapperMethod1();
wrapper.method1();
Wrapper wrapper2=new SourceWrapperMethod2();
wrapper2.method2();
}
}
类的适配器模式:当希望将一个类转换成满足另一个新接口的类时,可以使用类的适配器模式,创建一个新类,继承原有的类,实现新的接口即可。
对象的适配器模式:当希望将一个对象转换成满足另一个新接口的对象时,可以创建一个Wrapper类,持有原类的一个实例,在Wrapper类的方法中,调用实例的方法就行。
接口的适配器模式:当不希望实现一个接口中所有的方法时,可以创建一个抽象类Wrapper,实现所有方法,我们写别的类的时候,继承抽象类即可。

浙公网安备 33010602011771号