Detailed explanation of dyeing steamed bread case based on decorator mode in Java
This paper describes a case of dyed steamed bread implemented in Java based on decorator mode. Share with you for your reference, as follows:
Model definition
Decorator mode is to dynamically extend an object function without changing the original class file and using inheritance. It wraps the real object by creating a wrapping object, that is, decoration.
Decorative objects and real objects have the same interface, so that client objects can interact with decorative objects in the same way as real objects.
A decoration object contains a reference to a real object.
Two. Example of model
1. Mode analysis
Tainted steamed buns are the first mock exam to illustrate this pattern.
2. Decorator mode static class diagram
3. Code example
3.1 create steamed bread interface - ibread
3.2 realization of normal steamed bread
3.3 create an abstract decorator abstractbread
3.4 create colorant decorator - corndecorator
3.5 create sweet decorator
3.6 production of sweet corn steamed bread
4. Operation results
3、 Design principle of this mode
1 closed change part 2 "open close" principle 3 oriented to abstract programming 4 preferentially use combination rather than inheritance
4、 Use occasion
1. When we need to dynamically add a new function or responsibility to an existing object, we can consider using decorator mode.
2. When the responsibility of an object often changes or needs to be increased dynamically, avoid adding the method of inheriting subclass expansion to adapt to such changes, because this method will cause subclass expansion to be too fast and difficult to control. At this time, the decorator mode can be used.
5、 Decorator Pattern static class diagram
For more information about Java algorithms, readers who are interested can see the topics on this site: Java data structure and algorithm tutorial, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills