深圳网站建设素材网站,vps租用,比较好的网站建设哪家好,整站优化和单词目录
编辑
1. 策略模式概述#xff1a;
2. 主要角色#xff1a;
3. 实例场景#xff1a;
4. 具体实现步骤#xff1a;
步骤一#xff1a;定义策略接口
5. 使用策略模式的客户端代码#xff1a;
总结#xff1a;
我的其他博客 1. 策略模式概述#xff1a; 策…目录
编辑
1. 策略模式概述
2. 主要角色
3. 实例场景
4. 具体实现步骤
步骤一定义策略接口
5. 使用策略模式的客户端代码
总结
我的其他博客 1. 策略模式概述 策略模式是一种行为型设计模式它定义了一系列算法并将每个算法封装起来使它们可以相互替换。策略模式使得算法可以独立于客户端而变化从而使客户端可以选择不同的算法而不会影响到客户端的代码。 2. 主要角色 Context上下文 维护一个对策略对象的引用并在运行时切换不同的策略。 Strategy策略接口 定义了所有支持的算法的公共接口。通常是一个接口或抽象类。 ConcreteStrategy具体策略 实现了策略接口提供具体的算法实现。
3. 实例场景
考虑一个支付系统根据不同的支付方式采用不同的支付策略。策略模式可以使得新增支付方式时不必修改现有代码只需添加新的支付策略即可。
4. 具体实现步骤
步骤一定义策略接口
// Strategy 接口
public interface PaymentStrategy {void pay(int amount);
}步骤二实现具体的策略
// ConcreteStrategy1
public class CreditCardPayment implements PaymentStrategy {Overridepublic void pay(int amount) {System.out.println(Paid amount via Credit Card.);}
}// ConcreteStrategy2
public class PayPalPayment implements PaymentStrategy {Overridepublic void pay(int amount) {System.out.println(Paid amount via PayPal.);}
}步骤三定义上下文类
// Context
public class ShoppingCart {private PaymentStrategy paymentStrategy;public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy paymentStrategy;}public void checkout(int amount) {paymentStrategy.pay(amount);}
}5. 使用策略模式的客户端代码
public class Client {public static void main(String[] args) {ShoppingCart cart new ShoppingCart();// 选择支付策略PaymentStrategy creditCardPayment new CreditCardPayment();PaymentStrategy payPalPayment new PayPalPayment();// 设置支付策略cart.setPaymentStrategy(creditCardPayment);// 进行支付cart.checkout(100);// 切换支付策略cart.setPaymentStrategy(payPalPayment);// 进行支付cart.checkout(150);}
}总结
策略模式通过将算法封装在独立的策略类中使得算法的变化不影响到使用算法的客户端。这种灵活性和可维护性使得策略模式在面对多种算法选择时非常有用同时提高了代码的可扩展性。
我的其他博客
Git命令大全从基础到高级应用-CSDN博客
简单介绍一些其他的树-CSDN博客
什么是tomcattomcat是干什么用的-CSDN博客
TCP/IP 四层体系结构-CSDN博客
Redis新数据类型-Bitmaps-CSDN博客
腾讯-轻量应用服务器centos7中宝塔安装MySQL8.0出现内存不足-CSDN博客Synchronized 优化-CSDN博客腾讯-轻量应用服务器centos7中宝塔安装MySQL8.0出现内存不足-CSDN博客
【计算机网络】URL概念及组成-CSDN博客
【计算机网络】TCP socket编程-CSDN博客
枚举类的final修饰-CSDN博客
什么是RabbitMQ-CSDN博客