赞
踩
定义一系列的算法,把它们一个个封装起来,并且使他们可以相互替换此模式使得算法可以独立于使用它们的客户而变化
- // 策略接口(Algorithm Interface)
- interface PaymentStrategy {
- void pay(int amount);
- }
-
- // 具体策略类
- class CreditCardPayment implements PaymentStrategy {
- private String cardNumber;
- private String cvv;
-
- public CreditCardPayment(String cardNumber, String cvv) {
- this.cardNumber = cardNumber;
- this.cvv = cvv;
- }
-
- @Override
- public void pay(int amount) {
- System.out.println("使用信用卡支付 " + amount + " 元。");
- // 实现信用卡支付
- }
- }
-
- class PayPalPayment implements PaymentStrategy {
- private String email;
- private String password;
-
- public PayPalPayment(String email, String password) {
- this.email = email;
- this.password = password;
- }
-
- @Override
- public void pay(int amount) {
- System.out.println("使用PayPal支付 " + amount + " 元。");
- // 实现PayPal支付
- }
- }
-
- // 上下文类
- class PaymentContext {
- private PaymentStrategy paymentStrategy;
-
- public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
- this.paymentStrategy = paymentStrategy;
- }
-
- public void makePayment(int amount) {
- paymentStrategy.pay(amount);
- }
- }
-
- // 主类
- public class Main {
- public static void main(String[] args) {
- PaymentContext context = new PaymentContext();
-
- // 使用信用卡支付策略
- context.setPaymentStrategy(new CreditCardPayment("1234 5678 9012 3456", "123"));
- context.makePayment(100);
-
- // 使用PayPal支付策略
- context.setPaymentStrategy(new PayPalPayment("example@example.com", "password123"));
- context.makePayment(50);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。