结构型模式:Adapter(适配器)
2013-02-05 22:45
489 查看
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
相关文章推荐
- 设计模式笔记--结构型模式之一适配器 adapter
- 七、Adapter 适配器(结构型模式)
- 7种结构型模式之:适配器模式(Adapter):类适配器、对象适配器
- 结构型模式之适配器ADAPTER
- Adapter(适配器)--类对象结构型模式
- 设计模式之九:Adapter(适配器)—类对象结构型模式
- 【结构型模式】适配器(adapter)模式之23种java设计模式
- Adapter 适配器 (结构型模式)
- 设计模式:结构型模式:适配器(adapter)
- Adapter 适配器(结构型模式)
- 【设计模式基础】结构型模式 - 1 - 适配器(Adapter)
- Adapter 适配器(结构型模式)
- [设计模式-结构型]适配器(Adapter)
- [设计模式-结构型]适配器(Adapter)
- 设计模式七:Adapter(适配器)——类对象结构型模式
- 2.1 Adapter(适配器) -- 类/对象结构型模式
- 【结构型模式】adapter(适配器)
- 设计模式之适配器(Adapter)---类对象结构型模式
- 结构型模式-适配器 Structural Patterns- Adapter
- 结构型模式-适配器(adapter)