设计模式——适配器模式

9.适配器模式

9.1 对象适配器

是个这,有两种接口,都有各自的实现类,我现在要使IRoundPeg像IPeg规定的那样调用insertIntoHole方法来执行自己的insertIntoRoundHole方法的内容。那么通过写一个适配器就可以完成这个任务。

创建一个适配器,实现IPeg接口,在insertIntoHole调用IRoundPeg的insertIntoRoundHole方法即可实现

public interface IPeg {
    void insertIntoHole();
}
public interface IRoundPeg {
    void insertIntoRoundHole();
}
public class SquarePeg implements IPeg{

    @Override
    public void insertIntoHole() {
        System.out.println("SquarePeg的insertIntoHole方法");
    }
}
public class RoundPeg implements IRoundPeg{
    @Override
    public void insertIntoRoundHole() {
        System.out.println("RoundPeg的insertIntoRoundHole方法");
    }
}
public class RoundPegAdapter implements IPeg{
    private IRoundPeg iRoundPeg;

    public RoundPegAdapter(IRoundPeg iRoundPeg){
        this.iRoundPeg = iRoundPeg;
    }
    @Override
    public void insertIntoHole() {
        iRoundPeg.insertIntoRoundHole();
    }
}
public class Client {
    public static void main(String[] args) {

        IPeg squarePeg = new SquarePeg();
        squarePeg.insertIntoHole();


        IRoundPeg roundPeg = new RoundPeg();
        //如果不用适配器,调用的方法是这个insertIntoRoundHole方法
        roundPeg.insertIntoRoundHole();
        //如果用适配器,调用的适配器里的insertIntoHole方法,然后被转发到了roundPeg的insertIntoRoundHole方法
        IPeg roundPegAdapter = new RoundPegAdapter(roundPeg);
        roundPegAdapter.insertIntoHole();

    }
}
9.2 类适配器

使用继承的方式转发,替代了上述内置对象,这种叫类适配器

public class RoundPegAdapter2 extends RoundPeg implements IPeg{

    @Override
    public void insertIntoHole() {
        super.insertIntoRoundHole();
    }
}
9.3 双向适配器

把这两个接口都实现,然后都内置他们的对象。实现的接口方法都调用对方的方法,就可以实现。看源码。

public class TwoWayAdapter implements IRoundPeg , IPeg{
    
    private IPeg squarePeg;
    private IRoundPeg iRoundPeg;
    
    public TwoWayAdapter(IPeg squarePeg, IRoundPeg iRoundPeg){
        this.squarePeg = squarePeg;
        this.iRoundPeg = iRoundPeg;
    }
    
    
    @Override
    public void insertIntoHole() {
        iRoundPeg.insertIntoRoundHole();
    }

    @Override
    public void insertIntoRoundHole() {
        squarePeg.insertIntoHole();
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值