战略模式是一种行为设计模式,可以让你在运行时动态地改变对象的行为。在Java中,动态替换战略的行为可以通过接口和实现类来实现。
战略模式有三个重要部分:环境、战略界面和具体战略。环境类接收战略对象,并将执行过程委托给战略对象。战略界面定义了公共操作,具体战略是实现战略界面。
public interface Strategy { void strategyMethod(); } public class ConcreteStrategyA implements Strategy { public void strategyMethod() { System.out.println("执行策略A"); } } public class ConcreteStrategyB implements Strategy { public void strategyMethod() { System.out.println("执行策略B"); } } public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void contextMethod() { strategy.strategyMethod(); } }
以下是一个使用策略模式的简单例子。支付环境类接收支付策略对象,具体支付方式由选择的支付策略决定:
public interface PaymentStrategy { void pay(int amount); } public class CreditCardStrategy implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid " + amount + " using Credit Card"); } } public class PaypalStrategy implements PaymentStrategy { public void pay(int amount) { System.out.println("Paid " + amount + " using Paypal"); } } public class ShoppingCart { private PaymentStrategy paymentStrategy; public ShoppingCart(PaymentStrategy paymentStrategy) { this.paymentStrategy = paymentStrategy; } public void checkout(int amount) { paymentStrategy.pay(amount); } }
战略模式的主要优点是它能使你在运行过程中改变对象的行为。并且您可以独立于其它代码来定义新的策略。
ShoppingCart cart = new ShoppingCart(new CreditCardStrategy()); cart.checkout(100); cart = new ShoppingCart(new PaypalStrategy()); cart.checkout(200);
上述代码反映了运行时动态切换策略和扩展策略的能力。
本文链接:http://task.lmcjl.com/news/1319.html