This is my second article on getting started.
Writing in the front
Design patterns in Java can be divided into creative patterns, structural patterns, and behavioral patterns, each of which includes several specific design patterns.
Today we’ll look at the decorator pattern within the structural pattern.
The Decorator Pattern allows you to add functionality to the current object without changing the object’s structure.
There are many examples of decorator patterns that can be abstracted from life.
For example, drinking coffee in Starbucks will add milk (function) and sugar (function) to the coffee (object).
For example, if you eat gai rice in the canteen, you will give rice (object), add moo shu pork (function), and add braised pork in soy sauce (function).
And so on, after looking at the decorator pattern, as long as you are careful, you will find that there are many similar businesses everywhere in life.
Real business implements the decorator pattern
Next, we will implement the decorator mode according to the canteen business.
The business scenario
Student A got A pay rise today, and ordered A luxury set meal, braised pork with rice in soy sauce + braised pork with rice in soy sauce + chicken steak + fried egg. One of them only braised pork without rice, because too much carbohydrate is easy to gain weight.
From a developer’s point of view, be sure to consider this as the decorator pattern.
Cover rice (rice cover rice is also cover rice, don’t bar……) Is the object, braised pork in soy sauce, chicken steak, fried egg is a function, add new functions from the original object, and the original object structure has not changed, still can add new dishes (functions), the final calculation of the cost is undoubtedly to use the decorator mode.
So let’s do that in code.
Since there are many kinds of initial sets of Gai rice, we need to set the gaI rice class as abstract class. The initial sets (braise pork gaI rice, moo shu pork gaI rice, etc.) just need to inherit the abstract class of gaI rice.
Gai rice abstract class created, the next is to achieve braised meat gai rice class.
The cost method of the abstract class is realized and the price of braised pork is written in the method.
Of course, there will be a variety of gai rice, I will not achieve one.
Then it is the side dishes, in order to unify the management of side dishes and the maintenance consideration after the complexity of business functions;
We’re also going to create a garnish abstract class here, so all the garnish should inherit from the garnish abstract class;
The garnish abstract class inherits the garnish abstract class.
This design can be used in very friendly code to calculate the corresponding amount of money, see the final implementation method.
With that done, a decorator pattern is realized.
The next post will talk about the advantages and disadvantages of decorator mode, and when to use decorator mode, I hope you like!!