设计模式-适配器模式

设计模式目录:https://blog.youkuaiyun.com/qq_52681418/article/details/114828850

设计模式-适配器模式

将一个类的接口转换另外一个接口,让原本接口不兼容的类可以兼容。

1.比方说你有一个类:

public class Goods{
    public void myGoods(){
        System.out.println("这是一个类,这个方法是固定的。");
    }
}

2.然后你还有一个接口:

public interface GoodsInterface {
    void theGoods();
}

如果你此时,想通过GoodsInterface 接口来调用Goods中的Goods方法怎么实现呢?

public class Goods implements GoodsInterface{

   public void myGoods(){
       System.out.println("这是一个类,这个方法是固定的。");
   }

   public void theGoods() {
       myGoods();
   }
}

此时我们可用想到修改Goods类的来实现

public class Main {
   public static void main(String[] args) {
       GoodsInterface goodsInterface=new Goods();
       goodsInterface.theGoods();
   }
}

有时候我们不能修改Goods类,所以需要使用适配器来实现接口调用不适配的类。

3.适配器

//适配器实现接口,并继承子类
public class Adapter extends Goods implements GoodsInterface{

    public void theGoods() {
        super.myGoods();
    }
}

使用

public class Main {
    public static void main(String[] args) {
        GoodsInterface goodsInterface=new Adapter();
        goodsInterface.theGoods();
    }
}

此时就完成了不改变原有类的情况下,将类适配到接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值