Adapter pattern

1.Adapter 对象适配(Object)

假设我们要打桩,有两种类:方形桩 圆形桩.

 public class SquarePeg{
    public void insert(String str){
           System.out.println("SquarePeg insert():"+str);
    }
}

public class RoundPeg{
    public void insertIntohole(String msg){
           System.out.println("RoundPeg insertIntoHole():"+msg);
    }
}

现在有一个应用,需要既打方形桩,又打圆形桩.那么我们需要将这两个没有关系的类综合应用.假设RoundPeg我们没有源代码,或源代码我们不想修改,那么我们使用Adapter来实现这个应用:

 public class PegAdapter extends SquarePeg{
    private RoundPeg roundPeg;
    public PegAdapter(RoundPeg peg){
          
this.roundPeg=peg;
    }
    public void insert(String str){
           roundPeg.insertIntoHole(str);
    
}
}

 在上面代码中,RoundPeg属于Adaptee,是被适配者.PegAdapter是Adapter,将Adaptee(被适配者RoundPeg)和Target(目标SquarePeg)进行适配.实际上这是将组合方法(composition)和继承(inheritance)方法综合运用.

 PegAdapter首先继承SquarePeg,然后使用new的组合生成对象方式,生成RoundPeg的对象roundPeg,再重载父类insert()方法。从这里,你也了解使用new生成对象和使用extends继承生成对象的不同,前者无需对原来的类修改,甚至无需要知道其内部结构和源代码.

2.Adapter 类适配(Class)
use interface to meet customer requirement based on existing class
//Customer reuqire method/interface
public interface SquarePeg{
  public void insert(String str);
}

//Existing method/class
public class RoundPeg{
public void insertIntohole(String msg){
System.out.println("RoundPeg insertIntoHole():"+msg);
   }
}

//Adapter:
public class PegAdapter extends RoundPeg implements SquarePeg{

     public void insert(String str){ 
          insertIntoHole(str);
    
}
}

Customer call the adapter: PegAdapter, and the adaptee:RoundPeg be called by adapter.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值