Design Mode-decoration Mode

Source: Internet
Author: User

Design Mode-decoration Mode
Scenario settings

I get up in the morning, naked. At this time, I need to wear clothes. I need to wear pants first and then my coat.
How can I implement this process?

First, I am a naked person and can be seen by others:

Class Person {protected String name; protected String body; public void show () {System. out. println ("body ");}}

Then, I need to wear trousers first:

Class Trousers extends Person {private Person person; public Trousers (Person person) {this. person = person ;}@ Override public void show () {System. out. println ("pants worn"); person. show ();}}

The reasonextendsPerson, because Trousers wear a Person and have the sameshowMethod, you can see it, and also ensure that the pants are converted into a person wearing pants through the Person, in essence into a person.
Next we need to wear clothes:

Class Tshirt extends Person {private Person person; public Tshirt (Person person) {this. person = person ;}@ Override public void show () {System. out. println ("dressed"); person. show ();}}

Similarly, after a decoration object Person is passed into the Tshirt, the Person will first get dressed during show.

The code for getting a person dressed neatly on the client is as follows:

public static void main(String[] args){    Person xiaomingPerson = new Person();    Trousers trousers = new Trousers(xiaomingPerson);    Tshirt tshirt = new Tshirt(trousers);    tshirt.show();}

The decoration mode has this characteristic. After decoration A packs an object P, decoration A is A kind of P. After decoration B packs the decoration A, decoration B is still A kind of P.
Therefore, when calling the show method of the most primitive object P, first call the show method of the outer decoration Class B, then enter the show METHOD OF A, and finally the show METHOD OF THE P object. Therefore, the final performance of the decoration class is similarRecursionFrom the outside to the inside.

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.