Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/45457903
I. Overview
Transforms the interface of one class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not work together because of incompatible interfaces to work together.
Second, applicability
1. You want to use a class that already exists, and its interface doesn't fit your needs.
2. You want to create a reusable class that can work with other unrelated classes or classes that are not predictable (that is, those that might not necessarily be compatible with the interface).
3. (For object adapter only) you want to use some subclasses that already exist, but it is not possible to subclass each to match their interfaces. The object adapter can be adapted to its parent class interface.
Third, participants
1.Target defines a domain-specific interface used by the client.
2.Client is in collaboration with objects that match the target interface.
3.Adaptee defines an already existing interface that needs to be adapted.
4.Adapter Adapter for Adaptee interface to target interface
Four, class diagram
V. Examples
Target
Package com.lyz.design.adapter;/** * Defines the target interface * @author Liuyazhuang * */public interface target { void Adapteemethod (); void Adaptermethod ();}
Adaptee
Package com.lyz.design.adapter;/** * Adapter class * @author Liuyazhuang * */public class Adaptee {public void Adapteemethod () { System.out.println ("Adaptee method!");} }
Adapter
Package com.lyz.design.adapter;/** * Target Implementation class * @author Liuyazhuang * */public class Adapter implements Target { pri Vate adaptee adaptee; Public Adapter (Adaptee adaptee) { this.adaptee = adaptee; } public void Adapteemethod () {Adaptee.adapteemethod ();} public void Adaptermethod () {System.out.println ("Adapter method!");} }
Client
Package com.lyz.design.adapter;/** * Testing class * @author Liuyazhuang * */public class Test {public static void main (string[] Arg s) {target target = new Adapter (new Adaptee ()); Target.adapteemethod (); Target.adaptermethod ();}}
result
Adaptee method! Adapter method!
On the Java design mode--Adapter mode (Adapter)