9.4 class adapters
In addition to the Object Adapter mode, the adapter mode also has a form of class adapter mode,The main difference between the class adapter mode and the Object Adapter mode is that the relationship between the adapter and the adaptation is different. In the Object Adapter mode, the adapter and the adaptation are correlated, in the class adapter mode, the adapter and the adapter are inherited., The class adapter mode structure is shown in 9-5:
Figure 9-5 structure of the adapter Mode
According to the class adapter pattern structure, the adapter class implements the abstract target class interface target, and inherits the adapter class, in the request () of the adapter class () the method calls the inherited specificrequest () method of the adaptor class to implement adaptation.
The typical class adapter code is as follows:
class Adapter extends Adaptee implements Target {public void request() {specificRequest();}}
Because Java, C #, and other languages do not support multi-class inheritance, the use of class adapters is subject to many restrictions. For example, if the target abstract class is not an interface but a class, it cannot be used; in addition, if the adapter is a final class, the class adapter cannot be used. In Java and other object-oriented programming languages, object adapters are used in most cases, and class adapters are rarely used.
|
Thoughts In a class adapter, can an adapter adapt to multiple adaptors? If yes, how should we implement it? If not, why? |
|
9.5 bidirectional Adapter
When using the Object Adapter, if the adapter also contains a reference to the target class and the adaptation class, the adapter can call the method in the target class through it, the target class can also use it to call methods in the adapter class. The adapter is a two-way adapter, and its structure is 9-6:
Figure 9-6 bidirectional adapter Structure
The implementation of two-way adapters is complex. The typical code is as follows:
Class adapter implements target, adaptee {// At the same time, maintain reference to the abstract target class and adaptability to private Target target; private adaptee; Public adapter (target) implements this.tar get = target ;} public adapter (adaptee) {This. adaptee = adaptee;} public void request () {adaptee. specificrequest ();} public void specificrequest () {target. request ();}}
In actual development, we seldom use two-way adapters.
[Author: Liu Wei http://blog.csdn.net/lovelion]