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.