OOP作业——适配器设计模式及继承和多态在其中的应用

适配器设计模式一般有三种类型:类的适配器模式、对象的适配器模式、接口的适配器模式。

(1)类的适配器模式

public interface Targetable {  
    /* 与原类中的方法相同 */  
    public void method1();  
  
    /* 新类的方法 */  
    public void method2();  
}  

public class Source {  	  
    public void method1() {  
        System.out.println("this is original method!");  
    }  
}  

public class Adapter extends Source implements Targetable {  
    @Override  
    public void method2() {  
        System.out.println("this is the targetable method!");  
    }  
} 

public class AdapterTest {  
    public static void main(String[] args) {  
        Targetable target = new Adapter();  
        target.method1();  
        target.method2();  
    }  
}

输出结果:    
this is original method!
this is the targetable method!

类图:

 

在类的适配器模式中,我们利用继承(Inheritance),构造了一个被适配者(Source类)的子类,再利用多态性(Polymorphism),让子类重写目标接口(Targetable)中我们需要的方法,这样就可以在不改变原有类(Source类)代码的基础上,实现目标接口要求的方法。

(2)对象的适配器模式

public class Source{
    public void method1() { };
}

public interface Targetable {
    void method1();
    void method2();
}

public class Adapter implements Targetable {  
    private Source source;  
    public Adapter(Source source){  
        super();  
        this.source = source;  
    }  
    @Override  
    public void method2() {  
        System.out.println("this is the targetable method!");  
    }  
  
    @Override  
    public void method1() {  
        source.method1();  
    }  
} 

public class AdapterTest {  
    public static void main(String[] args) {  
        Source source = new Source();  
        Targetable target = new Adapter(source);  
        target.method1();  
        target.method2();  
    }  
}  

类图

 

在对象的适配器模式中,源类(Source类)缺少目标接口中的部分方法,我们想要一个类既可以调用源类中已有方法,又实现了目标接口。那么我们构造一个适配器(Adapter类)实现目标接口(Targetable),并且有一个源类的实例。利用多态性(Polymorphism),重写源类需要的方法,即利用源类实例调用其方法;实现接口方法。

(3)接口的适配器模式

public interface ISourceable {  
    public void method1();  
    public void method2();  
    public void method3();  
}

public abstract class BaseAdapter implements ISourceable{  
    public void method1() {}
    public void method2() {}
    public void method3() {}
}

public class ListAdapter extends BaseAdapter {  
	// 不用全部实现方法,只需要实现需要的就可以了
    public void method3(){  
        System.out.println("the method3!");  
    }  
}  

类图:

 

在接口的适配器模式中,目标接口(ISourceable类)所要求的方法很多,但很多时候实现该接口的类(ListAdapter)并不需要所有的方法。我们可以创建一个抽象类(BaseAdapter类),实现所有方法。之后当我们写其他类需要实现该接口的时候,利用继承(Inheritance),继承抽象类,即可只重写我们需要的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值