Adapter Mode: Adapter
Adapt the existing interface to meet the requirements of the new interface.
The adapter requires a reference to the object to be adapted.
The adapter is packaged with multiple adapters that are appearance mode.
The intent of the adapter mode is to change the interface to meet customer expectations, and the intent of the façade mode is to provide a simplified interface to the subsystem.
It's easy to relate to the appearance pattern. The appearance mode provides a unified interface for accessing a group of interfaces in a subsystem.
Compare the differences among the following three
The adorner does not change the interface but joins the responsibility;
The adapter transforms an interface into another interface;
The appearance makes the interface more simple
Adapter Pattern Class Diagram:
The following procedure simulates the call and fly action of ducks and turkeys. Suppose you lack a duck object, you fit a turkey into a duck and use a turkey as a duck.
1. Define the Duck interface
Package net.dp.adapter.ducks; Public interface Duck {public void quack (); public void Fly ();
2. Define Turkey Interface
Package net.dp.adapter.ducks; Public interface Turkey {public void gobble (); public void Fly ();
3. Define a turkey's implementation class
Package net.dp.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");} }
4. Implement the turkey Adapter
Package net.dp.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 ();}} }
So turkeyadapter can be used as a duck!!
5. Test class
Package net.dp.adapter.ducks; public class Ducktestdrive {public static void Main (string[] args) { Wildturkey Turkey = new Wildturkey (); Duck turkeyadapter = new Turkeyadapter (Turkey); Testduck (Turkeyadapter); } static void Testduck (Duck Duck) { duck.quack (); Duck.fly (); }}
Design mode-Adapter mode