Home » Java » Java design pattern (5) -- adapter mode

Java design pattern (5) -- adapter mode

The

adapter pattern is primarily for remediation. Why do you say so? Take the observer model in Chapter 1:

1, JDK observer Observer, is an interface, if we have a Male class to implement the observer function, then the direct implementation of the Observer interface can, however, if need be, not only have the function of Observer to User (another class) function, I have how do you do? Here, class adapter will play a role in


public, class, Male, extends, User, implement, Observer{
}

only implements the target class and implements the Observer interface, which implements our purpose above. This adapter is called class adapter.


2, JDK in the observed Observable is a class, similar to the above requirements, we need to have the Male class, Observable observed the function, but also has the functionality of the User class, that this is how to do? It is best not to let User go to the Observable class inheritance, the inheritance system will break the original ring because the Java inheritance only allowed to inherit a class, we use the class adapter will not be able to meet our needs, so you must use the.

object adapter
class Male extends User{
Private Observable observable;
//get set method
}

This is the

object adapter, using combined User and Observable mode, so that the two classes of functions we can use. Of course, this is not the best way, because the actual demand in more than one class Male, there may be other classes need to have similar needs, we repeat this definition is too much trouble so, we define a public class, as an adapter, Male classes inherit directly from the public will be able to meet the demand of the.

adapter
class BaseUserObservable extends User{
Private Observable observable;
//get set method
}
Class, Male, extends, BaseUserObservable {
}

is the object adapter,.


according to different purposes, can also be divided into custom adapter and default adapter. What is said above, is a strong purpose, what is needed to achieve what function, custom adapter, and the adapter is in default, we implement some interface, such as eliminating unnecessary method:


interface A{
Public, void, method1 ();
Public, void, method2 ();
Public, void, method2 ();
}

has a A interface, there are three methods, assumptions, we have a C class, need to inherit A, you must override this three methods, at this time, if we really value to use only method1, then the other two method code is redundant, this time you can use the default adapter.


class B implement A{
Public void (method1) {}
Public void (method2) {}
Public void (method2) {}
}

so, our class C just needs to inherit B, and then rewrite the methods we need to


class, C, extends, B {
Public, void, method1 () {
...
}
}

Latest