保持先进的软件设计模式

越抽象,就越无法被challenge,无论业务怎么变,这个系统总有一些无法被challenge的代码,以至于系统能够很快地基于这些代码,完成“回退”,并花最小的代价实现符合业务需求的功能。

因为追求可更改的颗粒度,所以从底层的原始抽象interface,到部分抽象abstract class,到完全实例class

// 抽象的支付接口 - 难以被挑战的核心抽象
interface PaymentStrategy {
    void pay(double amount);
}

// 抽象的通知接口 - 另一个稳定的抽象
interface NotificationStrategy {
    void notify(String message);
}

// 具体的支付方式实现
class CreditCardPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using Credit Card");
    }
}

class PayPalPayment implements PaymentStrategy {
    public void pay(double amount) {
        System.out.println("Paid " + amount + " using PayPal");
    }
}

// 具体的通知方式实现
class EmailNotification implements NotificationStrategy {
    public void notify(String message) {
        System.out.println("Email notification: " + message);
    }
}

class SMSNotification implements NotificationStrategy {
    public void notify(String message) {
        System.out.println("SMS notification: " + message);
    }
}

// 使用这些抽象的订单处理系统
class OrderProcessor {
    private PaymentStrategy paymentStrategy;
    private NotificationStrategy notificationStrategy;

    public OrderProcessor(PaymentStrategy paymentStrategy, NotificationStrategy notificationStrategy) {
        this.paymentStrategy = paymentStrategy;
        this.notificationStrategy = notificationStrategy;
    }

    public void processOrder(double amount) {
        paymentStrategy.pay(amount);
        notificationStrategy.notify("Your order of $" + amount + " has been processed.");
    }

    // 允许动态更改策略
    public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void setNotificationStrategy(NotificationStrategy notificationStrategy) {
        this.notificationStrategy = notificationStrategy;
    }
}

// 使用示例
public class AbstractStableSystem {
    public static void main(String[] args) {
        PaymentStrategy creditCard = new CreditCardPayment();
        NotificationStrategy email = new EmailNotification();

        OrderProcessor processor = new OrderProcessor(creditCard, email);
        processor.processOrder(100.0);

        // 业务需求变化:使用PayPal支付和SMS通知
        processor.setPaymentStrategy(new PayPalPayment());
        processor.setNotificationStrategy(new SMSNotification());
        processor.processOrder(200.0);

        // 假设未来需要添加新的支付方式(如比特币),只需要实现PaymentStrategy接口
        // 例如:
        // processor.setPaymentStrategy(new BitcoinPayment());
        // processor.processOrder(300.0);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值