The principle of opening and closing of design patterns (with code display)

The open-closed principle is one of the most basic principles in object-oriented design. Its core idea is that a software entity should be open for extension and closed for modification. In other words, when the function of a module needs to be extended, it should be implemented by adding code instead of modifying the original code.

The realization of the opening and closing principle needs to follow the following two principles:

1. Abstract the mutable and immutable parts. Abstract the unchanged part to achieve reusability and stability; abstract the changed part and provide it to the outside in the form of an interface.

2. Inheritance and polymorphism. When a module needs to be extended, it should be implemented through inheritance and polymorphism instead of directly modifying the original code.

The main advantages of the open-closed principle include:

1. Improve system maintainability. Since there is no need to modify the original code, the risk and cost of modification are relatively small. This makes the system easier to maintain.

2. Improve the scalability of the system. The changed part is abstracted and provided to the outside in the form of an interface, which increases the flexibility and scalability of the system. This makes the system more adaptable to changing requirements.

3. Improve code reusability. Abstract the invariant parts so that they can be reused in different systems. This helps improve code efficiency and reliability.

4. Strengthen teamwork. The principle of opening and closing can promote collaboration between teams and reduce dependencies and coupling between codes. This helps teams develop more efficiently.

In short, the principle of opening and closing is one of the most basic principles in object-oriented design, which can improve the maintainability, scalability and reusability of the system. When designing software, it is important to follow the open-closed principle to make it easier to modify and extend the code in the future.


In Python, you can demonstrate the application of the open-closed principle by writing a base class. Suppose we have a graphics class Shapethat has a method to calculate the area area(), and now we need to add a method to calculate the perimeter perimeter(), but we don't want to affect the original code.

We can abstract the variable method perimeter()into an abstract method according to the realization principle of the opening and closing principle, and then realize it through inheritance and polymorphism.

The sample code is as follows:

from abc import ABC, abstractmethod

class Shape(ABC):
    """
    抽象基类
    """
    @abstractmethod
    def area(self):
        pass
    
    @abstractmethod
    def perimeter(self):
        pass

class Rectangle(Shape):
    """
    矩形类
    """
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

class Circle(Shape):
    """
    圆形类
    """
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

    def perimeter(self):
        return 2 * 3.14 * self.radius

if __name__ == '__main__':
    rect = Rectangle(4, 6)
    print("矩形面积:", rect.area())
    print("矩形周长:", rect.perimeter())

    circle = Circle(3)
    print("圆形面积:", circle.area())
    print("圆形周长:", circle.perimeter())

Here we define an abstract base class Shape, and there are two abstract methods area()and perimeter()these abstract methods are variable. Then we define two specific classes Rectangle and Circle, which inherit from the Shape class respectively, and implement area()and perimeter()methods, which are specific.

In this way, we can extend its functionality without modifying the original code. For example, if you need to add a triangle class, you only need to inherit from the Shape class and implement area()the perimeter()sum method.

In short, by abstracting the variable part, and using inheritance and polymorphism to extend the function of the code, the realization of the principle of opening and closing can be followed, making the code more robust and flexible.

Guess you like

Origin blog.csdn.net/q6115759/article/details/130860048
Recommended