策略设计模式是一种行为模式,其中我们有多种算法/策略来完成一项任务,所使用的算法/策略留给客户选择。 各种算法选项封装在单独的类中。

在本教程中,我们将学习在Java中实现策略设计模式。

UML表示形式:

首先,我们来看一下策略设计模式的UML表示形式:

在这里,我们有:

  • 策略:定义我们打算执行的常见操作的界面
  • ConcreteStrategy:这些是使用不同算法来执行Strategy界面中定义的操作的实现类
  • 背景:任何需要改变行为并提及策略的事物

JDK中策略模式的一个流行示例是Collections.sort()方法中java.util.Comparator的用法。 我们可以将Collections.sort()方法视为上下文,并将其作为传递对象排序策略的java.util.Comparator实例。

实施策略模式:

众所周知,任何购物网站都提供多种付款方式。 因此,让我们使用此示例来实现策略模式。

我们将首先定义我们的PaymentStrategy接口:

 public interface PaymentStrategy { 
     void pay(Shopper shopper);  } 

现在,让我们定义两种最常见的付款方式,即货到付款和卡付款,作为两种具体的策略类:

 public class CashOnDeliveryStrategy implements PaymentStrategy { 
     @Override 
     public void pay(Shopper shopper) { 
         double amount = shopper.getShoppingCart().getTotal(); 
         System.out.println(shopper.getName() + " selected Cash On Delivery for Rs." + amount ); 
     }  }   public class CardPaymentStrategy implements PaymentStrategy { 
     @Override 
     public void pay(Shopper shopper) { 
         CardDetails cardDetails = shopper.getCardDetails(); 
         double amount = shopper.getShoppingCart().getTotal(); 
         completePayment(cardDetails, amount); 
         System.out.println( "Credit/Debit card Payment of Rs. " + amount + " made by " + shopper.getName()); 
     }  
     private void completePayment(CardDetails cardDetails, double amount) { ... }  } 

实施上下文:

定义了策略类之后,现在让我们定义一个PaymentContext类:

 public class PaymentContext {  
     private PaymentStrategy strategy;  
     public PaymentContext(PaymentStratgey strategy) { 
         this .strategy = strategy; 
     }  
     public void makePayment(Shopper shopper) { 
         this .strategy.pay(shopper); 
     }  } 

同样,我们的Shopper类看起来类似于:

 public class Shopper {  
     private String name; 
     private CardDetails cardDetails; 
     private ShoppingCart shoppingCart;  
     //suitable constructor , getters and setters     
     public void addItemToCart(Item item) { 
         this .shoppingCart.add(item); 
     }  
     public void payUsingCOD() { 
         PaymentContext pymtContext = new PaymentContext( new CashOnDeliveryStrategy()); 
         pymtContext.makePayment( this ); 
     }  
     public void payUsingCard() { 
         PaymentContext pymtContext = new PaymentContext( new CardPaymentStrategy()); 
         pymtContext.makePayment( this ); 
     }  } 

我们系统中的购物者可以使用一种可用的购买策略进行付款。 在我们的示例中,我们的PaymentContext类接受所选的支付策略,然后为该策略调用pay()方法。

策略与状态设计模式:

策略和状态设计模式都是基于接口的模式,可能看起来相似,但有一些重要区别:

  • 状态设计模式定义了各种状态,其中策略模式更多地讨论了不同的算法
  • 在状态模式中,存在从一种状态到另一种状态的过渡。 另一方面,策略模式中的所有策略类都是相互独立的

请随时探索状态设计模式

结论:

通过此快速教程,我们现在知道如何实现策略设计模式。

它是最常用的设计模式之一,并遵循“ 打开/关闭”原则 。 因此,要添加新策略,我们可以简单地创建一个额外的策略类。 但是,请注意,我们必须在这里更新客户端代码,因为客户端选择了要调用的策略。

翻译自: https://www.javacodegeeks.com/2019/09/strategy-design-pattern-java.html

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐