Home> Java> javaTutorial> body text

Example analysis of strategy pattern and state pattern in java design patterns

王林
Release: 2023-04-17 20:10:01
forward
863 people have browsed it

Usage scenarios

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 changes in behavior, we can define a Abstract state class that provides object behavior interface. Specific state-related behaviors are implemented by its subclasses.

Strategy mode: The word "strategy" is equivalent to algorithm. When algorithms need to be dynamically specified in the real system and can be replaced with each other, the calling interface of the algorithm can be abstracted. The specific algorithm is implemented by a specific strategy role. To implement, according to the Liskov substitution principle, any place where a parent class appears can be replaced with its subclass, which meets our business needs.

Comparison

Although both abstract the standard calling interface of the parent class, the specific behavior is implemented by the subclass, and the environment object also contains references to the parent class, but The application scenarios of these two modes are completely different. For example: If you go to an ATM to withdraw money, if your account is frozen, you cannot withdraw money normally. Here, your bank account has at least two statuses: frozen and unfrozen. You would not think of using the strategy pattern to solve such a business solution. Another example is shopping mall discounts. There are many discount strategies. Children's products are 30% off, and elderly products are 50% off. This problem is not related to the state mode. You can't say that the products here have an elderly state and a child state!

ATM withdrawal case analysis

Designed roles: cashier, account, ATM machine.

Use case diagram

For the sake of simplicity, let’s analyze the withdrawal use case.

Example analysis of strategy pattern and state pattern in java design patterns

Basic event path

(1) The withdrawer inserts the bank card and enters the password;

(2) Selects the withdrawal operation and enters Withdrawal amount;

(3) Waiting for cash withdrawal to withdraw money.

In this use case, if the withdrawer's account has been 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 from the two classes that identify the withdrawal and the withdrawal person. Taking into account that the withdrawr not only has the use case of withdrawing money, we generalize the withdrawal into a transaction.

Modeling

Example analysis of strategy pattern and state pattern in java design patterns

Use Case Realization

Withdrawal: Realization of the basic event path.

Example analysis of strategy pattern and state pattern in java design patterns

Refined domain model

The ATMSystem boundary object is introduced here as the controller responsible for interacting with the user (the ATM operation interface for interacting with the user). Trade is the class responsible for processing user transactions.

The withdrawer inserts the bank card and enters the password. ATMSystem is responsible for passing the message to verify the account information to the Trade transaction class. Trade verifies whether the user exists based on the passed account password, and then passes the processing completion message to ATMSystem. Boundary objects are reflected to the user.

Some classes in the analysis model

Example analysis of strategy pattern and state pattern in java design patterns

##Withdrawal design——Application status mode

The status of the account is divided into frozen status and Activation status. The account can conduct transactions when it is activated, but cannot make any transactions when it is frozen. During account verification, the status of the current account should be returned. If the account is frozen, an error message will be returned directly when the withdrawal operation is performed. The state diagram is represented as follows:

Example analysis of strategy pattern and state pattern in java design patterns

Withdrawal application state mode structure diagram:

Example analysis of strategy pattern and state pattern in java design patterns

In the account verification stage, if the account is In the frozen state, it will directly return to DeadAccount to refuse all transactions, otherwise it will return to ActiveAccount to process subsequent transactions.

Schematic code:

For simple implementation, the boundary object ATMSystem is omitted here.

User account information abstract class

///  /// 用户账号信息 ///  public abstract class Account { ///  /// 账号 ///  private string account; ///  /// 密码 ///  private string pwd; public abstract decimal getBalance(decimal d); }
Copy after login
##Freeze account class
///  /// 冻结账户类 ///  public class DeadAccount:Account { public override decimal getBalance(decimal d) { return 0; } }
Copy after login

激活账户类

///  /// 激活账户类 ///  public class ActiveAccount:Account { public override decimal getBalance(decimal d) { return d; } }
Copy after login

交易类

///  /// 交易类 负责用户交易处理的类 ///  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; } ///  /// 商业逻辑 取款 ///  ///  ///  public decimal GetBalance(decimal d) { return this.account.getBalance(d); } }
Copy after login

用户类

///  /// 取款人 ///  public class User { ///  /// 用户账号信息 ///  private Account account; ///  /// 交易处理类 ///  private Trade trade; public User(Account a, Trade t) { this.account = a; tthis.trade = t; } ///  /// 用户登录类 ///  public void Login() { trade.VolidateLogin(account); } ///  /// 取款 ///  ///  ///  public decimal GetBalance(decimal d) { return trade.GetBalance(d); } }
Copy after login

客户端代码

class Client { static void Main(string[] args) { //开始用户取款,默认是激活账户 ActiveAccount aa = new ActiveAccount(); Trade t = new Trade(); User u = new User(aa,t); //先登录,后取款 u.Login(); Console.WriteLine(u.GetBalance(100)); Console.ReadLine(); } }
Copy after login

用户必须先登录(插入银行卡,输入密码,点确定),才能选择取款业务(选择取款)。登录之后,返回的账号对象作为trade类成员,当进行取款业务的时候直接引用该账号成员获得取款信息。如果该账号属于冻结账号,则直接返回0。否则返回取款的值。

商品折扣案例

案例描述:某家超市国庆节为了促销,某些类商品打折,比如运动鞋打8折、秋装打9折等,张三去购物为了一双运动鞋、一件秋装、一瓶洗发水。。。,张三买完东西回家,心想今天自己总共“赚”了多少钱?

案例分析:商家对于商品打折可能有很多策略,这里使用策略模式,封装商品打折策略,这样以便以后扩展了打折策略,不用去修改原来的代码,具有很好的灵活性。

模式涉及的角色:

抽象策略角色:通常由一个接口或者抽象实现;

具体策略角色:包装了相关的算法和行为;

环境角色:包含抽象策略角色的引用,最终供用户使用。

商品折扣案例设计图

Example analysis of strategy pattern and state pattern in java design patterns

顾客购物涉及到的角色有:购物车、商品、收银台、抽象策略角色和具体策略角色。

购物车:是摆放商品的容器,提供添加和删除操作;

商品:商品实体,有类型,商品名、价格等属性;

收银台:负责收钱,主要是计算顾客购买所有商品的价格和折扣总额;

抽象策略角色:提供折扣策略接口。

具体策略角色:实现具体折扣算法。

商品折扣示意代码:

///  /// 具体商品类 ///  public class goods { ///  /// 商品类型 ///  public string Type { set; get; } ///  /// 商品名称 ///  public string Name { get; set; } ///  /// 商品价格 ///  public decimal Price { get; set; } }
Copy after login

抽象策略角色

///  /// 抽象策略接口 ///  public interface IDiscountStrategy { decimal GetDiscount(goods g); }
Copy after login

具体策略角色

///  /// 秋装打折策略 ///  public class AutumnDressDiscountStrategy:IDiscountStrategy { #region IDiscountStrategy Members public decimal GetDiscount(goods g) { return (decimal)0.9 * g.Price; } #endregion } ///  /// 运动鞋打折策略 ///  public class SportShoesDiscountStrategy:IDiscountStrategy { #region IDiscountStrategy Members public decimal GetDiscount(goods g) { return g.Price * (decimal)0.8; } #endregion }
Copy after login

购物车

///  /// 购物车类 负责商品的维护 ///  public class ShoppingCar { private List goodsList=new List(); ///  /// 将商品加入到购物车 ///  ///  public void AddGoods(goods g) { goodsList.Add(g); } ///  /// 将商品从购物车当中移除 ///  ///  public void RemoveGoods(goods g) { goodsList.Remove(g); } public List GoodsList { get { return goodsList; } } }
Copy after login

收银台角色

///  /// 收银台 ///  public class CashierDesk { ///  /// 购物车 ///  private ShoppingCar shoppingCar; ///  /// 策略字典 ///  private Dictionary strategies; public CashierDesk(ShoppingCar sc, Dictionary s) { this.shoppingCar = sc; this.strategies = s; } ///  /// 获得所有商品的价格 ///  ///  public decimal GetTotalPrice() { return shoppingCar.GoodsList.Sum(p => p.Price); } ///  /// 获得所有商品的总的折扣 ///  ///  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; } }
Copy after login

客户端代码

class Client { static void Main(string[] args) { ShoppingCar sc = new ShoppingCar(); Dictionary discountD = new Dictionary(); //向购物车中加入商品 sc.AddGoods(new goods {Name="NIKE鞋 ",Price=100,Type="运动鞋" }); sc.AddGoods(new goods { Name = "秋装", Price = 200, Type = "秋装" }); sc.AddGoods(new goods { Name = "苹果", Price = 300, Type = "水果" }); //配置折扣策略 discountD.Add("运动鞋", new SportShoesDiscountStrategy()); discountD.Add("秋装", new AutumnDressDiscountStrategy()); CashierDesk cd = new CashierDesk(sc, discountD); //得到所有商品总价 Console.WriteLine(cd.GetTotalPrice()); //得到所有商品折扣价 Console.WriteLine(cd.GetTotalDiscount()); Console.ReadLine(); } }
Copy after login

策略模式优点与缺点:

优点

封装了算法不稳定性,易于以后业务策略的扩展。

缺点

每种策略对应于一个具体策略角色类,会增加系统需要维护的类的数量。

The above is the detailed content of Example analysis of strategy pattern and state pattern in java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!