结构型模式:Adapter(适配器)

本文通过一个具体的编程示例介绍了适配器模式的应用,详细解释了如何使用适配器来连接不同接口的对象,使得原本不兼容的类能够协同工作。通过实例演示了适配器类如何封装原始类的方法,实现接口转换,从而解决不同组件之间的兼容性问题。

http://en.wikipedia.org/wiki/Adapter_pattern


   


/* The OLD */
class SquarePeg {
   private double width;
   public SquarePeg( double w )       { width = w; }
   public double getWidth()           { return width; }
   public void   setWidth( double w ) { width = w; }
}

/* The NEW */
class RoundHole {
   private int radius;
   public RoundHole( int r ) {
      radius = r;
      System.out.println( "RoundHole: max SquarePeg is " + r * Math.sqrt(2) );
   }
   public int getRadius() { return radius; }
}

// Design a "wrapper" class that can "impedance match" the old to the new
class SquarePegAdapter {

   // The adapter/wrapper class "has a" instance of the legacy class
   private SquarePeg sp;

   public SquarePegAdapter( double w ) { sp = new SquarePeg( w ); }

   // Identify the desired interface
   public void makeFit( RoundHole rh ) {
      // The adapter/wrapper class delegates to the legacy object
      double amount = sp.getWidth() - rh.getRadius() * Math.sqrt(2);
      System.out.println( "reducing SquarePeg " + sp.getWidth() + " by " + ((amount < 0) ? 0 : amount) + " amount" );
      if (amount > 0) {
         sp.setWidth( sp.getWidth() - amount );
         System.out.println( "   width is now " + sp.getWidth() );
      }
   }
}

class AdapterDemoSquarePeg {
   public static void main( String[] args ) {
      RoundHole        rh = new RoundHole( 5 );
      SquarePegAdapter spa;

      for (int i=6; i < 10; i++) {
         spa = new SquarePegAdapter( (double) i );
         // The client uses (is coupled to) the new interface
         spa.makeFit( rh );
      }
   }
}
RoundHole: max SquarePeg is 7.0710678118reducing SquarePeg 6.0 by 0.0 amountreducing SquarePeg 7.0 by 0.0 amountreducing SquarePeg 8.0 by 0.9289321881345245 amount width is now 7.0710678118654755reducing SquarePeg 9.0 by 1.9289321881345245 amount width is now 7.0710678118654755

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值