适配器模式--缺省适配器,类适配器,对象适配器

模式思想
改变一个类的对外接口(增加或减少),以满足不同外部调用者的需求;

角色成员
目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
需要适配的类(Adaptee):需要适配的类或适配者类。
适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。

3种实现形式

适配的接口

public interface ITarget {

    public void internet();

    public void bluetooth();

}

- -缺省适配器- -

这里写图片描述

Adpater负责适配的接口的所有默认实现,其他需要适配的类只要继承自它,则完成适配;

Adapter

public class Adapter implements ITarget{

    //缺省适配器,和其他两种稍有不同

    @Override
    public void internet() {
        // TODO Auto-generated method stub
        //Empty Method
    }

    @Override
    public void bluetooth() {
        // TODO Auto-generated method stub
        //Empty Method
    }

}

Adaptee

public class Adaptee extends Adapter {

    public void  internet(){
        System.out.println("I can surf the internet... ::"+Adaptee.class);
    }

}

- - 类适配器- -

这里写图片描述

适配器(Adapter)继承某一个需要的类(Adaptee),保留它原来的方法,同时实现适配的接口(ITarget),添加Adaptee中缺少的方法

Adapter

public class Adapter extends Adaptee implements ITarget{

    //类适配器

    @Override
    public void bluetooth() {
        // TODO Auto-generated method stub
        System.out.println("I can use the bluetooth...::"+Adapter.class);
    }

}

Adaptee

public class Adaptee {

    public void  internet(){
        System.out.println("I can surf the internet... ::"+Adaptee.class);
    }

    public void phoneCall(){
        System.out.println("I can make a phone call...::"+Adaptee.class);
    }

}

- - 对象适配器- -

这里写图片描述

适配器(Adapter)包含需要适配的类(Adaptee)的一个实例对象,在Adaptee能够实现的功能,由这个实例对象完成,缺少的方法由Adapter实现;

Adapter

public class Adapter implements ITarget{

    //对象适配器

    private Adaptee adaptee;

    public Adapter(Adaptee adaptee){
        this.adaptee = adaptee;
    }


    @Override
    public void internet() {
        // TODO Auto-generated method stub
        this.adaptee.internet();
    }

    @Override
    public void bluetooth() {
        // TODO Auto-generated method stub
        System.out.println("I can use the bluetooth...");
    }

}

Adaptee

public class Adaptee {

    public void  internet(){
        System.out.println("I can surf the internet... ::"+Adaptee.class);
    }

    public void phoneCall(){
        System.out.println("I can make a phone call...::"+Adaptee.class);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值