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

被折叠的 条评论
为什么被折叠?



