Behavior design mode and behavior design mode
Overview of behavioral design patterns
The behavior mode focuses on the behavior of objects. This type of mode needs to abstract the behavior that may change and achieve the scalability of the entire architecture through encapsulation. The behavior to be encapsulated by these models is exactly the most unstable part of the software architecture, and the most likely to be expanded. Encapsulate these behaviors and use abstract features to provide the possibility of expansion.
Implementation Mechanism:
Use the Inheritance Mechanism to distribute actions among classes
It uses Object combinations instead of inheritance to describe how a group of objects collaborate to complete tasks that a single object cannot complete.
(1) template method mode
Question:
We usually encounter the following problem: We know the key steps required by an algorithm or process, and determine the execution sequence of these steps. However, the specific implementation of some clustering is unknown, or the implementation of some clustering is related to the specific environment.
Life scenarios:
A simple order processing requirement: a customer can order multiple goods (also known as the order items) in a single order, and the sales price of the goods is calculated based on the import price of the goods. Some goods can be discounted, while others cannot. Each customer has a credit line, and the total price of each order cannot exceed the customer's credit line.
Based on the above business, we can know the steps required to process an order:
1. traverse the list of order list items and accumulate the total prices of all goods (calculate the sales price according to the order list items)
2. Obtain the customer's credit line based on the customer's number
3. Write the customer number, the total price of the order, and the list of order items to the database.
However, we cannot determine how to calculate the sales price of the Shipping item, how to obtain the customer's credit line based on the customer's number, and how to write the order information into the database.
The template method mode encapsulates steps that we do not know the specific implementation into abstract methods and provides specific methods to call them in the correct order (these methods are collectively referred to as template methods ), this constitutes an abstract base class. Child classes inherit from this abstract base class to implement the abstract methods of each step aggregation, while the workflow is controlled by the parent class.
Public abstract class extends actorder {
Public Order placeOrder (int customerId, List orderItemList ){
Int total = 0;
For (int I = 0; I <orderItemList. size (); I ++ ){
OrderItem orderItem = (OrderItem) orderItemList. get (I );
Total + = getOrderItemPrice (orderItem) * orderItem. getQuantity ();
}
If (total> getSpendingLimit (customerId )){
Throw new BusinessException ("credit limit exceeded" + getSpendingLimit (customerId ));
}
Int orderId = saveOrder (customerId, total, orderItemList );
Return new OrderImpl (orderId, total );
}
Public abstract int getOrderItemPrice (OrderItem orderItem );
Public abstract int getSpendingLimit (int customerId );
Public abstract int saveOrder (int customerId, int total, List orderItemList );
}
Move the unchanged behavior to the superclass and remove repeated code in the subclass to reflect its advantages. When the unchanged and variable behaviors are mixed in the method, the unchanged behavior will be repeated in the subclass, the template method mode is to move these unchanged behaviors to a superclass to avoid repeated code.
This is a simple mode, but it is widely used. The reason is simple because only the inheritance relationship is used in this mode.
Because of its own defects, the inheritance relationship has been detained by experts as "evil. Experts warn about the use of Delegate-related (aggregate) systems instead of inheritance relationships, and the use of interfaces instead of abstract class inheritance as much as possible, so that these cainiao will "look at inheritance differently ".
In fact, inheritance still has many advantages. It seems that the disadvantages are even more obvious. The rational use of the inheritance relationship can still play a good role in your system design. The template method mode is an example.
(2) Strategy Mode
Question:
There is often a problem in the business with a set of algorithms. In different cases, we may use different algorithms. We need to find a flexible and simple design method: encapsulate each algorithm into an independent class with a common interface, so that they can be replaced with each other.
Life scenarios:
It is a very complicated problem for people in the sales department to quote a price to the customer. For example:
The full price is quoted for common customers or new customers;
Discounts are offered to the price quoted by the old customer based on the customer's service life;
A certain discount is given to the price quoted by major customers based on the cumulative consumption amount of the major customers;
We also need to consider the quantity and amount purchased by the customer. For example, although the customer is a new user, there will be a certain discount if the number of purchases at a time is very large or the total amount is very high;
In addition, the quoter's position also determines whether he has the permission to make a certain floating discount on the price;
In short, the quotation to the customer is very complicated, and the sales staff take different strategies in different situations.
Public class Price {
/** @ Param goodsPrice product sales price
* @ Param customerType customer type
* @ Return: the price that should be quoted to the customer */
Public double quote (double goodsPrice, String customerType ){
If (customerType. equals ("regular customer ")){
System. out. println ("No discounts for new customers or common customers ");
Return goodsPrice;
} Else if (customerType. equals ("old customer ")){
System. out. println ("5% discount for old customers ");
Return goodsPrice * (1-0.05 );
} Else if (customerType. equals ("major account ")){
System. out. println ("10% discount for major customers ");
Return goodsPrice * (1-0.1 );
}
Return goodsPrice;
}
}
The price class contains all the quotation calculation algorithms, making the price class, especially the quotation method complicated and difficult to maintain. What should I do?
Public class Price {
Public double quote (double goodsPrice, String customerType ){
If (customerType. equals ("regular customer ")){
Return this. calcPriceForNormal (goodsPrice );
} Else if (customerType. equals ("old customer ")){
Return this. calcPriceForOld (goodsPrice );
} Else if (customerType. equals ("major account ")){
Return this. calcPriceForLarge (goodsPrice );
}
Return goodsPrice;
}
Private double calcPriceForNormal (double goodsPrice ){...}
Private double calcPriceForOld (double goodsPrice ){... }
Private double calcPriceForLarge (double goodsPrice ){...}
}
Think about the problem, but it's just moving from the quote calculation method to the price class. If there are 100 or more such calculation methods, this will make the price class very huge, difficult to maintain. In addition, maintenance and expansion both need to modify the existing code, which is very bad and violates the open-close principle.
In addition, this is often the case when different computing methods are used.
For example, during the company's anniversary, all customers will receive an additional 3% discount. during seasonal promotions, regular customers will receive an additional 2% discount, while regular customers will receive an additional 3% discount, major customers increase the discount by 5%. This means that the quote calculation method is often modified or switched. After the promotion time, we have returned to the normal price system. In the current price category, the quote calculation method is fixed to call various calculation methods, which makes it difficult to switch and call different calculation methods, you need to modify the call code in if-else every time.
A reasonable solution for solving the above problems is the policy mode.
The policy mode allows the algorithm to change without affecting the client. Rule mode separates behavior from environment. The environment class is responsible for maintaining and querying behavior classes, and various algorithms are provided in specific policy classes. Because the algorithm and environment are independent, the increase, decrease, and modification of the algorithm will not affect the environment and the client.
To solve scenario problems based on the policy mode, the design is as follows:
Public interface Baojia {
Public double baojia (double price );
}
Public class Content {
Private Baojia bj;
Public Content (Baojia bj ){
Super ();
This. bj = bj;
}
Public double daZhe (double price ){
Return bj. baojia (price );
}
}
Public class LaoKeHuYear3_5 implements Baojia {
@ Override
Public double baojia (double price ){
Return price *. 75;
}
}
Public class NewKenHu implements Baojia {
@ Override
Public double baojia (double price ){
If (price> 10000 ){
Return price * (1-0.2 );
}
Return price;
}
}
Public class DaKeHu implements Baojia {
@ Override
Public double baojia (double price ){
Return price * 0.5;
}
}
Public class Test {
Public static void main (String [] args ){
Baojia bj = new LaoKeHuYear3_5 ();
Content c = new Content (bj );
Double p = c. daZhe (1000 );
System. out. println (p );
}
}
(3) Observer (Observer) Mode
Question:
In software systems, we sometimes need to define a one-to-many dependency. let multiple observer objects listen to a topic object at the same time. When the status of the topic object changes, all observer objects are notified so that they can update themselves automatically.
Life scenarios:
The name and price of commodities in online stores have changed. If the system can automatically notify members, the online stores will be different from the traditional stores.
Code implementation: Define the theme class
Public class product extends Observable {
Private String name;
Private float price;
Public String getName (){
Return name;
}
Public void setName (String name ){
This. name = name;
// Set the Change Point
SetChanged ();
Yyobservers (name );
}
Public float getPrice (){
Return price;
}
Public void setPrice (float price ){
This. price = price;
// Set the Change Point
SetChanged ();
NotifyObservers (new Float (price ));
}
}
Code implementation: Define the observer
Public class NameObserver implements Observer {
Private String name = null;
Public void update (Observable obj, Object arg ){
If (arg instanceof String ){
Name = (String) arg;
System. out. println ("NameObserver: name changet to" + name );
}
}
}
Public class PriceObserver implements Observer {
Private float price = 0;
Public void update (Observable obj, Object arg ){
If (arg instanceof Float ){
Price = (Float) arg). floatValue ();
System. out. println ("PriceObserver: price changet to" + price );
}
}
}
Public class Test {
Public static void main (String args []) {
Product product = new Product ();
NameObserver nameobs = new NameObserver ();
PriceObserver priceobs = new PriceObserver ();
// Add the observer
Product. addObserver (nameobs );
Product. addObserver (priceobs );
Product. setName ("orange red ");
Product. setPrice (9.22f );
}
}
(4) Command mode
Question:
In software systems, "behavior requestor" and "behavior implementers" are usually "tightly coupled ". However, in some cases, such as "record, undo/Redo, and transaction" operations, it is not suitable for tight coupling that cannot withstand changes. In this case, how can we decouple "behavior requestor" from "behavior implementer? Abstract A group of behaviors as objects to achieve loose coupling between them.