Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Strategy pattern and State pattern in java Design pattern

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "the case analysis of strategy pattern and state pattern in java design pattern". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "case analysis of strategy pattern and state pattern in java design pattern".

Working with scen

State mode: when the behavior of an object changes with the change of the state of the object, in order to decouple multiple judgment conditions and encapsulate the change of behavior, we can define an abstract state class and provide the interface of object behavior. The specific state-related behavior is implemented by its subclasses.

Policy pattern: the word "policy" is equivalent to the algorithm, when the real system needs to specify the algorithm dynamically and can replace each other, the calling interface of the algorithm can be abstracted, and the specific algorithm implementation is realized by the specific policy role. According to the Leeb replacement principle, wherever there is a parent class, it can be replaced by its subclass, which meets our business needs.

Compare

Although both of them abstract the calling interface of the parent class specification, the specific behavior is implemented by the subclass, and the environment object also contains the reference of the parent class, the application scenarios of the two patterns are completely different. For example, if you go to the ATM to withdraw money, if your account is frozen, you cannot withdraw money normally. Here your bank account has at least two states: frozen and unfrozen. You should not think of using a strategic model to solve such a business solution. For example, shopping malls offer discounts, there are many discount strategies, 30% discount for children's products and 50% discount for elderly products. This problem has nothing to do with the status model. You can't say that there are old people and children here!

A case study of ATM withdrawal

Designed to the role: payer, account, ATM.

Use case diagram

For simplicity here, analyze the withdrawal use case.

Basic event path

(1) the drawer inserts the bank card and enters the password

(2) Select the withdrawal operation and enter the withdrawal amount

(3) waiting for banknotes to be issued and withdrawn.

In this use case, if the withdrawal account is frozen, an optional event path occurs and the withdrawal use case is terminated.

The key business requirement is the fact that the user withdraws money, so domain modeling can start with identifying withdrawals and withdrawals. Here, considering that the withdrawals are not only the use case of withdrawals, we generalize withdrawals into transactions.

Modeling

Use case materialization

Withdrawal: the realization of the basic event path.

Refine the domain model

Here, the boundary object ATMSystem is introduced as the controller responsible for interacting with the user (the ATM interface that interacts with the user), and Trade is the class responsible for handling user transactions.

The payer inserts the bank card to enter the password, and ATMSystem is responsible for passing the message of verifying the account information to the Trade transaction class. Trade verifies whether the user exists according to the passed account password, and then passes the finished message to ATMSystem, which is the boundary object to reflect to the user.

Some classes in the analysis model

Withdrawal Design-Application status Mode

The status of the account can be divided into frozen state and active state. The account can be traded in the active state, but no transactions can be made in the frozen state. When verifying the account, the status of the current account should be returned. If the account is frozen, the error message will be returned directly when the withdrawals are performed. The state diagram is shown as follows:

Withdrawal application status pattern structure diagram:

In the verification stage, if the account is frozen, then directly return to DeadAccount to decline all transactions, otherwise return to ActiveAccount to process subsequent transactions.

Cosmetic code:

Here, for simple implementation, the boundary object ATMSystem is omitted.

Abstract class of user account information

/ user account information / public abstract class Account {/ account / private string account; / password / private string pwd; public abstract decimal getBalance (decimal d);}

Freeze account class

/ / freeze account class / public class DeadAccount:Account {public override decimal getBalance (decimal d) {return 0;}}

Activate account class

/ / activate account class / public class ActiveAccount:Account {public override decimal getBalance (decimal d) {return d;}}

Transaction category

/ / transaction class responsible for user transaction processing / public class Trade {/ private Account account; public Account VolidateLogin (Account a) {/ / query the database to validate the user exists / / For Example this.account = new DeadAccount (); return this.account } / Business logic withdrawal / public decimal GetBalance (decimal d) {return this.account.getBalance (d);}}

User class

/ public class User {/ user account information / private Account account; / transaction processing class / private Trade trade; public User (Account a, Trade t) {this.account = a; tthis.trade = t } / user login class / public void Login () {trade.VolidateLogin (account);} / withdrawal / public decimal GetBalance (decimal d) {return trade.GetBalance (d);}}

Client code

Class Client {static void Main (string [] args) {/ / start user withdrawal. The default is to activate the account ActiveAccount aa = new ActiveAccount (); Trade t = new Trade (); User u = new User (aa,t); / / log in first, then withdraw u.Login () Console.WriteLine (u.GetBalance); Console.ReadLine ();}}

Users must log in (insert bank card, enter password, click OK) before they can select withdrawal business (choose withdrawal). After logging in, the returned account object is a member of the trade class, and the account member is directly referenced to get the withdrawal information when carrying out the withdrawal business. If the account belongs to a frozen account, return 0 directly. Otherwise, the value of withdrawal is returned.

Case of commodity discount

Case description: in order to promote National Day in a supermarket, some goods are on sale, such as 20% discount on sneakers and 10% discount on autumn clothes. Zhang San goes shopping for a pair of sneakers, an autumn dress and a bottle of shampoo. no, no, no. Zhang San went home after shopping and wondered how much money he had "earned" today.

Case study: merchants may have many strategies for merchandise discounting. here we use the strategy model to encapsulate the commodity discount strategy, so as to expand the discount strategy in the future, without having to modify the original code, with good flexibility.

The roles involved in the pattern:

Abstract policy role: usually implemented by an interface or abstract

Specific strategy roles: packaging related algorithms and behaviors

Environment role: contains references to abstract policy roles that are ultimately available to the user.

Case design diagram of commodity discount

The roles involved in customer shopping are: shopping cart, merchandise, cashier, abstract strategy role and specific strategy role.

Shopping cart: a container for goods, providing add and delete operations

Commodity: commodity entity, with type, commodity name, price and other attributes

Cashier: responsible for collecting money, mainly calculating the prices and discounts of all goods purchased by customers

Abstract policy role: provides discount policy interface.

Specific strategy role: implement specific discount algorithm.

Product discount indication code:

/ specific commodity category / public class goods {/ commodity type / public string Type {set; get;} / public string Name {get; set } / Commodity price / public decimal Price {get; set;}}

Abstract policy role

/ Abstract Policy Interface / public interface IDiscountStrategy {decimal GetDiscount (goods g);}

Specific strategic roles

/ / Autumn discount strategy / public class AutumnDressDiscountStrategy:IDiscountStrategy {# region IDiscountStrategy Members public decimal GetDiscount (goods g) {return (decimal) 0.9 * g.Price } # endregion} / Sports shoes discount policy / public class SportShoesDiscountStrategy:IDiscountStrategy {# region IDiscountStrategy Members public decimal GetDiscount (goods g) {return g.Price * (decimal) 0.8;} # endregion}

Shopping Cart

/ the shopping cart category is responsible for the maintenance of the goods / public class ShoppingCar {private List goodsList=new List (); / add the goods to the shopping cart / public void AddGoods (goods g) {goodsList.Add (g) Remove items from the shopping cart / public void RemoveGoods (goods g) {goodsList.Remove (g);} public List GoodsList {get {return goodsList;}

Cashier role

/ cashier / public class CashierDesk {/ shopping cart / private ShoppingCar shoppingCar; / Policy Dictionary / private Dictionary strategies; public CashierDesk (ShoppingCar sc, Dictionary s) {this.shoppingCar = sc; this.strategies = s Get the price of all goods / public decimal GetTotalPrice () {return shoppingCar.GoodsList.Sum (p = > p.Price);} / get the total discount of all goods / public decimal GetTotalDiscount () {decimal sum = 0 IDiscountStrategy idiscountStrategy; foreach (goods g in shoppingCar.GoodsList) {idiscountStrategy=strategies.SingleOrDefault (p = > p.Key = = g.Type) .value; if (idiscountStrategy! = null) {sum + = idiscountStrategy.GetDiscount (g);}} return sum;}}

Client code

Class Client {static void Main (string [] args) {ShoppingCar sc = new ShoppingCar (); Dictionary discountD = new Dictionary (); / / add goods sc.AddGoods (new goods {Name= "NIKE shoes", Price=100,Type= "sneakers"}) to the shopping cart Sc.AddGoods (new goods {Name = "autumn wear", Price = 200, Type = "autumn wear"}); sc.AddGoods (new goods {Name = "apple", Price = 300, Type = "fruit"}); / / configure discount strategy discountD.Add ("sneakers", new SportShoesDiscountStrategy ()); discountD.Add ("autumn wear", new AutumnDressDiscountStrategy ()) CashierDesk cd = new CashierDesk (sc, discountD); / / get the total price of all goods Console.WriteLine (cd.GetTotalPrice ()); / / get the discount price of all goods Console.WriteLine (cd.GetTotalDiscount ()); Console.ReadLine ();}}

Advantages and disadvantages of the policy model:

Advantages

It encapsulates the instability of the algorithm and is easy to expand the business strategy in the future.

Shortcoming

Each policy corresponds to a specific policy role class, which increases the number of classes that the system needs to maintain.

Thank you for reading, the above is the content of "case analysis of strategy pattern and state pattern in java design pattern". After the study of this article, I believe you have a deeper understanding of the problem of case analysis of strategy pattern and state pattern in java design pattern, and the specific use needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report