[Headfirst Design Mode Study Notes] 7 adapter mode and appearance Mode

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

1. Role of the adapter: convert one interface to another. We can look at it as a conversion header of a socket.

2. The key to constructing an adapter:Implemented the Target Interface and held the instance of the adapter.The adapter uses the following method: the client calls the adapter method through the target interface to send a request to the adapter. The adapter uses the adapter interface to convert the request to one or more called interfaces of the backend. Here is an example of an adapter where a turkey impersonates a duck:

We define two things:

One is duck:

Public interface duck {
Public void quack ();
Public void fly ();
}

One is Turkey:

Public interface Turkey {
Public void gobble ();
Public void fly ();
}

What we are doing now is to let the Turkey have the ability to pretend to be a duck, then we must map some of the capabilities of the Turkey to some of the capabilities of the duck, so we use an adapter class to process such mappings:

Public class turkeyadapterImplements duck{
Turkey;
Public turkeyadapter (Turkey){
This. Turkey = Turkey;
}
Public void quack (){
Turkey. Gobble ();
}
Public void fly (){
For (INT I = 0; I <5; I ++ ){
Turkey. Fly ();
}
}
}

In this class similar to a capability converter, we first specify the ability to convert to duck (implements duck ), the actual provider -- Turkey of this capability is placed inside the class in the form of member variables (Turkey;) and when an object is generated in this class, it is passed in (Public turkeyadapter (Turkey)). The next step is to define these capabilities-that is, to implement the methods defined by the interface.

In use, our intention is to let the turkey pretend to be a duck. Then we need to first create a turkey and then build a new turkeyadapter (Turkey )), pass the Turkey we have created into the system for processing. The turkeyadapter can be used as a duck.

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. Quack ();
Duck. Fly ();
}
}

This design reflects the good OO design principles:Use an object combination to encapsulate the adaptors.In addition, it binds the two through a combination of interfaces, rather than implementation-this is the design concept of an Object Adapter.

3. The difference between a class adapter and an Object Adapter is that the class adapter uses the Inheritance Method and inherits the adaption (Turkey in this example) and the target adapter (duck in this example. The Object Adapter implements the duck interface. In a specific call, it uses the internal Turkey member variable to provide specific and realistic capabilities. In this way, the two are combined. Through comparison, we can get the following features:

The Object Adapter not only adapts to a class, but also to any subclass of the class. In addition, the implemented methods can be combined by multiple methods, which is more flexible.

Class adapters implement some methods only when needed, instead of implementing the methods of the entire adapter like the Object Adapter, because they can directly use inheritance to make it more efficient.

In addition, it should be noted that, because Java cannot provide multiple inheritance, it cannot easily implement the class adapter layer.

4. An example of using an adapter in Sun Java is the iterator interface, which implements traversal of the set type.

5. You may find that the decorator mode and the adapter mode are similar. Let's make a comparison:

The decorator needs to add some new behaviors or responsibilities to the design and dynamically add and process them.While the adapter mode needs to convert one capability to another, and some static capabilities are finalized. The decoration can also achieve capability conversion and support adding new behavior,The adapter is just a variant of the ModifierAre used to wrap objects. From another point of view, the adapter will definitely convert the interface, but the decorator will not. In terms of intention,The modifier extends the behavior or responsibility of the encapsulated object by changing the interface, while the adapter changes the interface by converting the behavior of the encapsulated object.

6. The book introduces another new interface Change Mode-appearance mode (facade), which aims to simplify the interface. The appearance class does not encapsulate subsystems, but provides a simplified set interface. This is actually a simple concept. It not only simplifies the interface, but also decouples the customer from the component subsystem. Both the appearance and the adapter can wrap multiple classes, but the appearance is intended to simplify the interface, and the adapter's intention is to convert the interface into different interfaces.

The book provides an example of the appearance mode of the home theater, combining many component actions to complete a series of convenient methods for users:

Public class hometheaterfacade {
Amplifier amp;
Tuner;
Dvdplayer DVD;
Cdplayer CD;
Projector projector;
Theaterlights lights;
Screen screen;
Popcornpopper Popper;
Public hometheaterfacade (amplifier amp,
Tuner,
Dvdplayer DVD,
Cdplayer CD,
Projector projector,
Screen screen,
Theaterlights lights,
Popcornpopper Popper ){
This. amp = amp;
This. tuner = tuner;
This. DVD = DVD;
This. Cd = Cd;
This. projector = projector;
This. Screen = screen;
This. Lights = lights;
This. Popper = Popper;
} // Pass reference of each component to this object
Public void watchmovie (string movie ){
System. Out. println ("Get ready to watch a movie ...");
Popper. On ();
Popper. Pop ();
Lights. Dim (10 );
Screen. Down ();
Projector. On ();
Projector. widescreenmode ();
Amp. On ();
Amp. setdvd (DVD );
Amp. setsurroundsound ();
Amp. setvolume (5 );
DVD. On ();
DVD. Play (movie );
}
Public void endmovie (){
System. Out. println ("shutting movie theater down ...");
Popper. Off ();
Lights. On ();
Screen. Up ();
Projector. Off ();
Amp. Off ();
DVD. Stop ();
DVD. Eject ();
DVD. Off ();
}

Public void listentocd (string cdtitle ){
System. Out. println ("Get ready for an audiopile experence ...");
Lights. On ();
Amp. On ();
Amp. setvolume (5 );
Amp. setcd (CD );
Amp. setstereosound ();
CD. On ();
CD. Play (cdtitle );
}

Public void endcd (){
System. Out. println ("shutting down CD ...");
Amp. Off ();
Amp. setcd (CD );
CD. Eject ();
CD. Off ();
}

Public void listentoradio (double frequency ){
System. Out. println ("tuning in the airwaves ...");
Tuner. On ();
Tuner. setfrequency (frequency );
Amp. On ();
Amp. setvolume (5 );
Amp. settuner (tuner );
}

Public void endradio (){
System. Out. println ("shutting down the tuner ...");
Tuner. Off ();
Amp. Off ();
}
}

We can watch a movie in a simple and comfortable way using this appearance mode:

Public class hometheatertestdrive {
Public static void main (string [] ARGs ){
Amplifier amp = new amplifier ("Top-o-line amplifier ");
Tuner = new tuner ("Top-o-line AM/FM tuner", AMP );
Dvdplayer DVD = new dvdplayer ("Top-o-line DVD player", AMP );
Cdplayer Cd = new cdplayer ("Top-o-line CD player", AMP );
Projector projector = new projector ("Top-o-line projector", DVD );
Theaterlights lights = new theaterlights ("theater ceiling lights ");
Screen screen = new screen ("theater screen ");
Popcornpopper Popper = new popcornpopper ("popcorn popper ");
Hometheaterfacade hometheater =
New hometheaterfacade (AMP, tuner, DVD, CD,
Projector, screen, lights, Popper );
Hometheater. watchmovie ("Raiders of the Lost Ark ");
Hometheater. endmovie ();
}

Finally, we define the appearance mode: a unified interface is provided to access a group of interfaces in the subsystem. The appearance defines a high-level interface, making the subsystem easier to use.

7. We will introduce a new OO principle-the least knowledge principle (also known as law of Demeter): Just talk to your close friend. That is to say,When you are designing a system, regardless of any object, you should pay attention to what classes it interacts with and how it interacts with these classes. Minimize dependencies between classes.To address this principle, we have a series of rules that can be followed: For any object, in its internal methods, we should only call methods that fall within the following scope:

  • The object itself.
  • The object passed in as a parameter of the method.
  • Any object created or instantiated by this method.
  • Any other object member and method in the object.

Example of a car:

Public class car {
Engine engine; // component in the class. We can call its method.
Public Car (){
}

Public void start (Key key ){
Doors doors = new doors ();//Method to create an object, we can call its Method
Boolean authorized =Key. Turns ();//The input parameter. We can call its method.
If (authorized ){
Engine. Start ();
Updatedashboarddisplay ();//Object, we can call
Doors. Lock ();
}
Public void updatedashboarddisplay (){
}
}

Do not call a method on the object returned by a call to another method. If we do this, it is equivalent to distributing requests to the child of another object, and the coupling will increase. However, this principle will also bring about some drawbacks, resulting in more "packaging" classes being created to process communication with other components and increase Program Complexity and runtime performance.

Let's take an example of an exercise in the book and take a closer look at this very basic and important principle:

A case that does not comply with this principle:

Public class house {
Weatherstation station;
Public float gettemp (){
Return station. getthermometer (). gettemperature ();
}
}

This gettemp method involves an object returned by the call.

We can take this method apart to get a case that complies with this principle:

Public class house {
Weatherstation station;
Public float gettemp (){
Thermometer thermometer = station. getthermometer ();
Return gettemphelper (Thermometer );
}

Public float gettemperhelp (Thermometer thermometer ){
Return thermometer. gettemperature ();
}
}

But does it make sense? I am afraid there is no such thing in this simple example. In fact, we often use examples that violate this principle, such as system. Out. println ......, This tells us that this is not a golden rule. In appearance mode, we can see that the hometheaterfacade class follows this principle, which has the following benefits:The replacement and upgrade of a component does not affect us to watch a movie easily through the main function in the hometheatertestdrive test class.

Online Video:

Http://v.youku.com/v_show/id_XMjU2Njk1Mzc2.html

Http://v.youku.com/v_show/id_XMjU2Njk0NzE2.html

 

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.