开闭原则:软件设计的弹性与稳健性,项目代码讲解

267 阅读13分钟

image.png

开闭原则(Open-Closed Principle, OCP)是SOLID设计原则中的第二原则。由Bertrand Meyer在1988年提出,并由Robert C. Martin进一步推广。开闭原则指出,软件实体应对扩展开放,对修改关闭。这意味着设计时应该允许轻松添加新功能,而不需要修改现有代码。

肖哥弹架构 跟大家“弹弹” 业务中设计模式的使用,需要代码关注

欢迎 点赞,点赞,点赞。

关注公号Solomon肖哥弹架构获取更多精彩内容

历史热点文章

2. 开闭原则设计图:

设计一个电子商务平台的支付模块,该模块需要能够处理不同类型的支付方式,例如信用卡支付和PayPal支付。随着市场的发展,我们可能需要添加更多的支付方式,如微信支付、Apple Pay等。

3. 开闭原则解决什么:

开闭原则解决了软件中因需求变更导致的频繁修改问题。遵循此原则的系统可以在不修改现有代码的基础上,通过增加新的代码来扩展功能。

4. 开闭原则特点:

  • 扩展性:系统可以通过添加新代码来扩展功能。
  • 稳定性:现有代码库保持稳定,不受新功能添加的影响。
  • 灵活性:通过抽象和多态,系统可以灵活地适应变化。

5. 开闭原则缺点:

  • 设计复杂性:为了满足开闭原则,可能需要更复杂的设计,如使用设计模式。
  • 过度设计:在某些简单场景中,过度应用开闭原则可能导致设计过于复杂。

6. 开闭原则使用场景:

当面临需求频繁变更或预期将来会有变更时,应考虑使用开闭原则来设计系统。

7. 开闭原则案例

7.1 支付案例

重构示例

  • 考虑一个电子商务平台的支付系统,最初只支持信用卡支付,但未来可能需要支持更多支付方式。

重构前

    public class PaymentProcessor {
        public void processPayment(double amount) {
            // 信用卡支付逻辑
        }
    }

重构后

    public interface PaymentStrategy {
        boolean executePayment();
    }

    public class CreditCardPayment implements PaymentStrategy {
        public boolean executePayment() {
            // 信用卡支付逻辑
            return true;
        }
    }

    public class PayPalPayment implements PaymentStrategy {
        public boolean executePayment() {
            // PayPal支付逻辑
            return true;
        }
    }

    public class PaymentProcessor {
        private PaymentStrategy paymentStrategy;

        public PaymentProcessor(PaymentStrategy paymentStrategy) {
            this.paymentStrategy = paymentStrategy;
        }

        public void processPayment() {
            paymentStrategy.executePayment();
        }
    }
7.2 折扣案例

图书管理系统需要根据不同的会员等级应用不同的折扣策略。我们预期未来可能会增加更多的会员等级和折扣规则。

重构前的代码:

  • 硬编码编写所有的折扣逻辑
public class DiscountCalculator {
    public double calculateDiscount(double originalPrice, String membershipLevel) {
        switch (membershipLevel) {
            case "Gold":
                return originalPrice * 0.90; // Gold members get 10% off
            case "Silver":
                return originalPrice * 0.95; // Silver members get 5% off
            default:
                return originalPrice; // No discount for others
        }
    }
}

应用开闭原则的重构:

为了遵循开闭原则,我们将折扣逻辑抽象化,使其能够容易地扩展新会员等级和折扣规则,而不需要修改现有的DiscountCalculator类。

  1. 定义折扣策略接口 (DiscountStrategy.java)
public interface DiscountStrategy {
    double calculateDiscount(double originalPrice);
}
  1. 实现具体的折扣策略 (GoldDiscountStrategy.javaSilverDiscountStrategy.java)
public class GoldDiscountStrategy implements DiscountStrategy {
    public double calculateDiscount(double originalPrice) {
        return originalPrice * 0.90;
    }
}

public class SilverDiscountStrategy implements DiscountStrategy {
    public double calculateDiscount(double originalPrice) {
        return originalPrice * 0.95;
    }
}
  1. 修改折扣计算器以使用策略 (DiscountCalculator.java)
public class DiscountCalculator {
    private DiscountStrategy discountStrategy;

    public DiscountCalculator(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public double calculateDiscount(double originalPrice) {
        return discountStrategy.calculateDiscount(originalPrice);
    }
}
  1. 客户端代码 (Client.java)
public class Client {
    public static void main(String[] args) {
        DiscountStrategy goldDiscount = new GoldDiscountStrategy();
        DiscountCalculator calculator = new DiscountCalculator(goldDiscount);
        double discountedPrice = calculator.calculateDiscount(100.0);
        System.out.println("Discounted price for Gold member: " + discountedPrice);
        
        // Easily switch to a different discount strategy
        DiscountStrategy silverDiscount = new SilverDiscountStrategy();
        calculator.setDiscountStrategy(silverDiscount);
        discountedPrice = calculator.calculateDiscount(100.0);
        System.out.println("Discounted price for Silver member: " + discountedPrice);
    }
}

8. 参考开源框架:

许多开源框架如Spring Framework通过使用策略模式、工厂模式等设计模式来实现开闭原则。

9. 总结:

开闭原则是软件设计中的一个重要指导原则,它强调通过抽象和接口来设计灵活且易于扩展的系统。遵循开闭原则可以帮助我们构建出能够快速适应变化的软件系统,同时减少因需求变更导致的代码修改和潜在错误。虽然在实际应用中可能需要权衡设计复杂性和项目需求,但开闭原则无疑为软件的可持续发展提供了坚实的基础。

历史热点文章