Decoration mode of java Design Mode
Modifier mode definition: dynamically extends the functions of an object without changing the original class file and using inheritance. It creates a packaging object, that is, decoration, to package a real object.
Let's look at his UML diagram.
VcqxztK + highlight + 8Tjz + highlight + yellow/jEw1tbRodTxo6y/yellow + yellow/aPGJyIC8 + yellow/yPGJyIC8 + yellow/Jq6Os17C/yellow "brush: java; ">package decorator;public interface Work { public void paint();}
2. Son. java
Package decorator; public class Son implements Work {public void paint () {System. out. println (the Son draws a picture with a pencil .); }}
3. Mother. java
Package decorator; public class Mother implements Work {// private Work of the decorator; public Mother (work Work) {this. work = work;} private Mother () {} public void paint () {// The responsibilities of the mom decorator System. out. println (Mom is preparing for the color .); // Work. paint (); // System. out. println (the color is painted by the mother .); }}
4. Father. java
Package decorator; public class Father implements Work {// private Work of the decorator; public Father (work Work) {this. work = work;} private Father () {} public void paint () {// The responsibilities of the dad decorator System. out. println (dad is preparing for the frame .); // Work. paint (); // work. paint (); // work. out. println (my father has installed a frame for the painting .); }}
5. DecoratorTest. java
Package decorator; public class DecoratorTest {public static void main (String [] args) {// draw only pencil strokes Work = new Son (); work. paint (); System. out. println (); // In addition to drawing a pencil drawing, you must also draw the color work = new Mother (work); work. paint (); System. out. println (); // In addition to drawing a pencil drawing, drawing a color, and drawing a frame work = new Father (work); work. paint ();}}
Output:
The son drew a pencil drawing.
Mom is preparing for the painting.
The son drew a pencil drawing.
Mom painted the color.
Dad is preparing for the frame.
Mom is preparing for the painting.
The son drew a pencil drawing.
Mom painted the color.
Dad installed a frame for the painting.
After reading this example, do you understand how to use the decorator mode?