Small Talk on Design Patterns (5)—Open and Closed Principle

Column introduction

Column address

link

Column introduction

It mainly analyzes and summarizes the 23 common design patterns currently on the market one by one. I hope that interested friends can take a look and it will be continuously updated. I hope you can supervise me and we can learn and make progress together. Come on, everyone.
Insert image description here

open closed principle

The open-closed principle is an important principle in object-oriented design, which guides us to write scalable, maintainable and reusable code.

main idea

Software entities (classes, modules, functions, etc.) should be open to extension and closed to modification. In other words, when new functionality needs to be added, it should be achieved by extending the existing code rather than modifying the existing code.

Keyword summary

Expand

When requirements change, we hope to be able to easily add new functions or features without modifying existing code. This reduces the risk of introducing new bugs.

closed

Existing code should be stable and should not be affected by changes in requirements. Even if the requirements change, we should not modify the existing code. This protects existing code and prevents the introduction of new errors.

explain

abstractions and interfaces

By defining an abstract class or interface, we can abstract away the variable parts and define a set of public methods and properties. In this way, when we need to extend, we only need to implement new subclasses or implement new interfaces without modifying the existing code.

Polymorphism

By using polymorphism, we can dynamically choose between different implementations at runtime. In this way, we can implement new functions by extending existing classes or interfaces without modifying existing code.
Insert image description here

code example

// 定义一个接口
public interface Shape {
    
    
    void draw();
}

// 定义一个实现类
public class Circle implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("Drawing a circle");
    }
}

// 定义一个扩展类
public class Rectangle implements Shape {
    
    
    @Override
    public void draw() {
    
    
        System.out.println("Drawing a rectangle");
    }
}

// 定义一个客户端类
public class Client {
    
    
    public void drawShapes(List<Shape> shapes) {
    
    
        for (Shape shape : shapes) {
    
    
            shape.draw();
        }
    }
}

// 测试代码
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Client client = new Client();
        List<Shape> shapes = new ArrayList<>();
        shapes.add(new Circle());
        shapes.add(new Rectangle());
        client.drawShapes(shapes);
    }
}

Insert image description here

Code explanation

In the above code, we define a Shape interface, which has a draw() method. Then we defined an implementation class Circle and an extension class Rectangle, both of which implement the Shape interface.

In the client class Client, we define a drawShapes() method, which accepts a List parameter and loops to call the draw() method of each Shape object. In this way, we can add new graphics types by extending the Shape interface and implementing new subclasses without modifying existing code.

In the test code, we create a Client object and pass in a List containing Circle and Rectangle objects. Then call the drawShapes() method, which will call the draw() method of each graphics object in turn to output the corresponding graphics.

This sample code demonstrates how to use the open-closed principle to implement code extensions. By defining a public interface and implementing multiple subclasses, we can extend the functionality of the code without modifying the existing code.
Insert image description here

Advantages and Disadvantages

advantage

Scalability

The open and closed principle can make the system have good scalability. By defining abstract classes or interfaces and implementing new subclasses or interfaces, we can add new functionality without modifying existing code.

maintainability

The open-closed principle can improve the maintainability of code. By separating the mutable parts from the stable parts, we can more easily understand and modify the code. When requirements change, we only need to extend existing classes or interfaces without modifying existing code.

Reusability

The open-closed principle can increase code reusability. By defining abstract classes or interfaces and implementing new subclasses or interfaces, we can apply the same code logic to different scenarios.

High cohesion and low coupling

The open-closed principle can improve code cohesion and reduce code coupling. By encapsulating the variable parts in independent classes and interacting through interfaces, we can decompose the code into independent modules, thereby improving the cohesion of the code and reducing the coupling of the code.

shortcoming

Abstract design complexity

The open-closed principle may increase code complexity. By introducing abstract classes or interfaces, we need to define more classes and interfaces, which increases the complexity of the code.

Need to reserve extension points

The open-closed principle requires reservation of expansion points during design, which may increase the difficulty of design. If extension points are not reserved correctly, existing code may need to be modified.

May introduce over-design

The open-closed principle can lead to over-design. In order to achieve scalability, we may introduce too many abstract classes and interfaces, which may increase the complexity of the code and the difficulty of understanding it.
Insert image description here

Summarize

The open-closed principle is an important principle in object-oriented design. Its core idea is to be open to expansion and closed to modification. By defining abstract classes or interfaces and implementing new subclasses or interfaces, new functionality can be added without modifying existing code. This can improve the scalability, maintainability and reusability of the system, while reducing the coupling of the code and improving the cohesion of the code. However, the open-closed principle may also increase the complexity of the code and the difficulty of design, and the pros and cons need to be weighed in practical applications. In general, the open-closed principle is an important principle that helps build scalable, maintainable, and reusable systems.

Guess you like

Origin blog.csdn.net/weixin_74888502/article/details/133138347