Adapter pattern: Convert the interface of a class into another interface that the client expects. Adapters allow classes with incompatible interfaces to work together.
Understanding: In fact, the composition, object adapter is used, an object is passed in an object, and the method of the current object calls the method of the incoming object. . . .
example:
1. Duck, Turkey interface
package adapter.ducks; public interface Duck { public void quack(); public void fly(); }
package adapter.ducks; public interface Turkey { public void gobble(); public void fly(); }
2. Implementation of Duck and Turkey interfaces
package adapter.ducks; public class MallardDuck implements Duck { public void quack() { System.out.println("Quack"); } public void fly() { System.out.println("I'm flying"); } }
package adapter.ducks; public class WildTurkey implements Turkey { public void gobble() { System.out.println("Gobble gobble"); } public void fly() { System.out.println("I'm flying a short distance"); } }
3. Two adapters DuckAdapter and TurkeyAdapter classes
package adapter.ducks; import java.util.Random; public class DuckAdapter implements Turkey { Duck duck; Random rand; public DuckAdapter(Duck duck) { this.duck = duck; rand = new Random(); } public void gobble() { duck.quack(); } public void fly() { if (rand.nextInt(5) == 0) { duck.fly(); } } }
package adapter.ducks; public class TurkeyAdapter implements Duck { Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } public void quack() { turkey.gobble(); } public void fly() { for(int i=0; i < 5; i++) { turkey.fly(); } } }
4. Test class
package adapter.ducks; public class TurkeyTestDrive { public static void main(String[] args) { MallardDuck duck = new MallardDuck(); Turkey duckAdapter = new DuckAdapter(duck); for(int i=0;i<10;i++) { System.out.println("The DuckAdapter says..."); duckAdapter.gobble(); duckAdapter.fly(); } } }
package adapter.ducks; public class DuckTestDrive { public static void main(String[] args) { MallardDuck duck = new MallardDuck(); WildTurkey turkey = new WildTurkey (); Duck turkeyAdapter = new TurkeyAdapter(turkey); System.out.println("The Turkey says..."); turkey.gobble(); turkey.fly(); System.out.println("\nThe Duck says..."); testDuck(duck); System.out.println("\nThe TurkeyAdapter says..."); testDuck(turkeyAdapter); } static void testDuck(Duck duck) { duck.quack(); duck.fly(); } }