Adapter mode - Adapter
Wrap an object with an incompatible interface into a compatible object
Facade/Facade Mode - Facade
Wrap a bunch of objects to simplify the interface
Facade pattern is used when you need to simplify and unify a large interface or a group of complex interfaces
Facades decouple clients from a complex subsystem
To implement a facade, you need to compose subsystems into the facade, and then delegate the work to the subsystem to perform
More than one facade can be implemented for a subsystem
Decorator Mode - Decorator
wrapping an object to add new behaviors and responsibilities
===============================================================
Adapter pattern example
Make turkey duck to be compatible with parameter types of existing interfaces
Duck's interface
package adapter.duck; public interface Duck { public void quack(); public void fly(); }
concrete duck
package adapter.duck; public class MallardDuck implements Duck { @Override public void quack() { System.out.println("Quack"); } @Override public void fly() { System.out.println("I'm flying"); } }
turkey interface
package adapter.turkey; public interface Turkey { public void gobble(); public void fly(); }
specific turkey
package adapter.turkey; public class WildTurkey implements Turkey { @Override public void gobble() { System.out.println("Gobble"); } @Override public void fly() { System.out.println("I'm flying a short distance"); } }
Disguise a turkey as a duck
package adapter.turkey; import adapter.duck.Duck; /** * Adapter * Internally disguise the turkey as a duck */ public class TurkeyAdapter implements Duck { //adapted Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } /** * Delegate the combined object to complete the task */ @Override public void quack() { turkey.gobble(); } @Override public void fly() { for(int i=0;i<5;i++) { //The turkey needs to fly 5 times in a row to reach the duck to fly once turkey.fly(); } } }
Test: Make turkey compatible with interfaces that take duck types as parameters
package test; import adapter.duck.Duck; import adapter.duck.MallardDuck; import adapter.turkey.Turkey; import adapter.turkey.TurkeyAdapter; import adapter.turkey.WildTurkey; public class AdapterTest { public static void main(String[] args) { Duck duck = new MallardDuck(); Turkey turkey = new WildTurkey(); Duck turkeyAdapter = new TurkeyAdapter(turkey); System.out.println("The Turkey says:"); turkey.gobble(); turkey.fly(); System.out.println("\nThe Duck syas:"); testDuck(duck); System.out.println("\nThe TurkeyAdapter syas:"); testDuck(turkeyAdapter);//Through the adapter, let the turkey become a duck } private static void testDuck(Duck duck) { duck.quack(); duck.fly(); } }
===============================================================
Enumeration Adapter