越抽象,就越无法被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);
}
}