Decorative mode of design mode (7)

Source: Internet
Author: User

    1. What is decorative mode
      Decoration (Decorator) mode is also called packing mode. The ability to extend an object in a transparent manner to the client is an alternative to the inheritance relationship.

    2. Structure of the decoration mode

    3. Role and responsibilities of decorative mode

      Abstract component role: An abstract interface that is the parent interface of the decorated class and the adornment class.
      Specific component role: An implementation class for an abstract component.
      Abstract Decorative Role: Contains a reference to a component and defines an interface that is consistent with the abstract component.
      Specific decorative role: the implementation class for the abstract decorative role. Responsible for
      The specific decoration.

As an example, if we want to build a car right now, yes! It's the car.

As we all know, different car functions are different, some cars can run, nonsense! Some cars can fly, some cars can swim, some cars can jump ... Don't get excited, I'll give you an example.

According to the traditional object-oriented idea, we must first define a car's parent class, define in this parent class some functions that all cars have, such as run (), and then derive the various subclasses to inherit the car parent class, and then implement their own unique functions in the subclass. For example, I declare that a flycar inherits from car and then implements the parent class's run () in Flycar, implementing its own unique Fly () method. Do you think so, do not admit, the average person is Jiangzi think. I think so too, at first I was very proud, because I used the object-oriented thinking!!!

But what if I want to build a car that can swim and fly? Can I define a flyswimcar inherited from Car,ok, of course. However, with the development of science and technology, the function of cars more and more rich, you have to constantly define a variety of combinations of functions of the car, you should know the arrangement of the bar ~ ~ ~ This is obviously not in line with the programmer lazy personality.

So, there is the decorative mode. We read the code and explain.

First of all, define a car base class, of course, this must be an interface, you know, you can not directly new a car out, who knows this car is the car with which function. But this interface car should contain the most basic functions of the car.

//Car.javapublicinterface Car {    publicvoidrun();    // 显示车的功能    publicvoidshow();}

The most common car but to achieve this interface, the car can not do anything other than run. Yes, this is the legendary "sports car".

//RunCar.javapublicclass RunCar implements Car{    @Override    publicvoidrun() {        System.out.println("run...");    }    @Override    publicvoidshow() {        this.run();    }}

And then, I want to build a car that can fly, how to do?

Let's first define an abstract class cardecorator, what does this class do? is to pack the car, why is it abstract? Because you build a fly and build a car can swim, with the material what is certainly different, that is, the contents of the package is different, so, this cardecorator is defined in the packaging class common operation. Just like, before the transformation of an ordinary car, whether you are converted to fly or can swim car, you first get this ordinary car, get a normal car this operation is defined in the Cardecorator base class.

//cardecorator.java Public Abstract classCardecorator {PrivateCar car; Public Cardecorator(Car car) { This. car = car; }//Provide method to get the car before packaging    //Why to get the packaging before the car, nonsense, do not get before the car, how do you add new features?     //Then where is the method for adding features? I didn't see it, don't worry, look down, it must be a specific decorator to add specific features AH.      PublicCarGetcar() {returnCar } Public void Setcar(Car car) { This. car = car; }//In order to show the function of the car, the show () method is determined     Public Abstract void Show();}

Well, now we can build a car that can fly.

//flycardecorator.java Public  class flycardecorator extends cardecorator {     Public Flycardecorator(Car car) {Super(car); }@Override    //Display the function of the car     Public void Show() {//First show the original car's function, this know why in the cardecorator to get the car before the transformation.          This. Getcar (). Show (); This. Fly ();//Add new features} Public void Fly() {System.out.println ("Fly ..."); }}

In the same vein, we can build a car that can swim.

//swimcardecorator.java   Public  class   Swimcardecorator  extends  cardecorator  {  public  swimcardecorator  (car car) {  super (CAR); }  @Override  public  void  show  () { this . Getcar ( ). Show (); this . Swim (); } public  void  swim  () {System.out.println (  "swim ..." ); }} 

Jiangzi, the main function becomes very refreshing.

//mainclass.java Public classMainClass { Public Static void Main(string[] args) {Car car =NewRuncar ();        Car.show (); System. out. println ("--------------------"); Swimcardecorator Swimcar =NewSwimcardecorator (car);        Swimcar.show (); System. out. println ("--------------------"); Flycardecorator Flycar =NewFlycardecorator (car);        Flycar.show (); System. out. println ("--------------------"); }}

Operation Result:

run...--------------------run...swim...--------------------run...fly...--------------------

Oh ah, is not very refreshing. But you have a wood to find a problem, you say build a can fly can swim car, now only built a can run and SIWM, can run and fly car, also want to face ...

Everybody crossing, don't be excited!!! Build it right away. Build it right away.

Normal thinking is not jiangzi, I have a car, only run, sports car!!! Now change (decorate) a bit, can swim, then I hope can swim also can fly, how to do? Nonsense, of course, the car can be swimming to add a wing what. Isn't it? Well, you want to be right this time. That's what I was thinking.

Now let's change our main function:

//mainclass.java Public classMainClass { Public Static void Main(string[] args) {Car car =NewRuncar ();        Car.show (); System. out. println ("--------------------");//1Car Swimcar =NewSwimcardecorator (car);        Swimcar.show (); System. out. println ("--------------------");//2 3Car Flycar =NewFlycardecorator (Swimcar);        Flycar.show (); System. out. println ("--------------------"); }}

Changed three places, compared with the original main function, see No. Why are you so changed, you don't all think of it??? Forgot? Go up and look.

In order to adapt the main function to this change, we modify the other files. Let's take a look at:

Car flyCar = new FlyCarDecorator(swimCar);

Originally flycardecorator of the construction method is passed car, you are now passing swimcar,swimcar before the change is what type, yes, is the Swimcardecorator type. Spicy, you know now how to change it.

Are we going to let Cardecorator implement car interface?

Then the Run method not implemented in car is implemented separately in Flydecorator.

OK, the code should not be an error ...

Now look at the results of the operation:


How, I did not break the promise, said to you to build a can fly can swim to build for you. The key code is still spicy elegance!!! Hey, I didn't write the code, I just analyzed it.

However, some people may ask, you say change this to change this, say change that then change that, in the end the change is not reasonable? Alas, do not say, such a change, than before is really reasonable.

First, the invocation logic in the Main method, which has been said before, is certainly in line with most people's thinking habits.

Then, we look at the Cardecorator implementation car interface is not reasonable, we look at his sub-class Flydecorator, he inherited from Cardecorator,cardecorator realized the car interface, so, Flydecorator to implement the interface in car, car has two methods one is show () and run (), the Show () method in Cardecorator has been defined as an abstract method, has been flydecorator implemented, and now left run () method is not implemented, so, flydecorator to implement the Run () method, you think, flydecorator implementation of the Run method is reasonable??? I think it's very reasonable that you put a wing on the car so he can fly, he can't run? Maybe people run faster, maybe they run more elegant posture? So you also have to give Flydecorator the opportunity to modify the original function while changing the car, right? So I think it's very reasonable. Similarly, the run () method in the car interface is also implemented in the Swimcarsdecorator.

Decorative mode of design mode (7)

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.