“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”

What is the open and close principle?

The Open Closed Principle (OCP) is at the heart of all object-oriented principles. The goal of software design itself is to encapsulate change and reduce coupling, and the open and closed principle is the most direct embodiment of this goal. Other design principles often serve this purpose.

1.1 First, let’s look at the definition of the open and close principle:

Software entities like classes,modules and functions should be open for extension but closed for modifications, Classes, modules, functions, etc., should be open to extension but closed to modification.

This is also the core idea of the open and closed principle: open to expansion, closed to modification.

1.2 What does this mean?

  • Being open to extension means that existing code can be extended to accommodate new requirements or changes.
  • Being closed to changes means that once the class is designed, it can do its job on its own without making any changes to existing code

Ii. How to realize the principle of openness and closure?

“Requirements are always changing.” “No software in the world is constant.” Requirements are always changing, but for software designers, how to achieve flexible extension without modifying the original system. That’s what the open close principle does.

When we design systems, we cannot assume that once the requirements are identified, they will not change later. It’s not scientific or realistic. Since requirements are bound to change, how do we deal with them gracefully? How can the software be designed so that it is relatively easy to change, so that a change in requirements does not require the entire program to be started from scratch?

Open – close principle. The best way to design software that is easy to maintain and not prone to problems is to extend it more and change it less.

2.1 Dependency and abstraction

The core idea of open closure is to deal with abstract programming, not concrete programming, because abstraction is relatively stable. Make classes dependent on fixed abstractions, so they are closed to change; And through the object-oriented inheritance and polymorphic mechanism, can realize the inheritance of the abstract body, by overwriting its method to change the inherent behavior, to achieve a new extension method, so for extension is open. This is the basic idea for implementing the open and closed principle.

2.2 How to Open and Close the Floor

If the current design does not meet the open and closed principle, you must refactor. The commonly used design patterns mainly include Template Method and Strategy design patterns. Encapsulating changes is an important way to achieve this principle, by encapsulating the parts that often change into a class.

2.3 Importance of the open and close principle

1. Influence of open and close principle on test

The open and close principle keeps the original test code running, so we only need to test the extended code.

2. Open and close principle can improve reusability

In object-oriented design, all logic is composed from atomic logic, rather than implementing a single business logic in a single class. Only then can code be reused, and the smaller the granularity, the more likely it is to be reused.

3. Open and close principle can improve maintainability

Requirements for object-oriented development.

2.4 How to Use the Open close Principle

1. Abstract constraints

First, the extension is constrained by interface or abstract class, and the boundary of the extension is limited. Public methods that do not exist in the interface or abstract class are not allowed to appear. Second, parameter types and reference objects should use interfaces or abstract classes rather than implementation classes. Third, the abstraction layer should be kept as stable as possible and not be modified once determined.Copy the code

2. Metadata controls module behavior

Metadata is the data used to describe the environment and data. In plain English, it is called configuration parameters, which can be obtained from files or databases. The Spring container is a typical example of metadata Control module behavior, culminating in Inversion of Control.Copy the code

3. Formulate project charter

In a team, it is important to have a project charter, because the charter specifies conventions that all personnel must follow, and conventions are superior to configurations for the project.Copy the code

4. Encapsulate change

Encapsulating changes has two meanings. First, encapsulate the same change into an interface or abstract class. Second, encapsulate different changes into different interfaces or abstract classes. There should not be two different changes in the same interface or abstract class.Copy the code

Case analysis

Case 1: Draw shapes

Requirements: there are circles and ellipses, draw the corresponding shapes according to the requirements

public class GraphicEditor {

    public void draw(Shape shape) {
        if (shape.m_type == 1) {
            drawRectangle();
        } else if(shape.m_type == 2) { drawCircle(); }}public void drawRectangle(a) {
        System.out.println("Draw a rectangle.");
    }

    public void drawCircle(a) {
        System.out.println("Draw circles");
    }

    class Shape {
        int m_type;
    }

    class Rectangle extends Shape {
        Rectangle() {
            super.m_type=1; }}class Circle extends Shape {
        Circle() {
            super.m_type=2; }}}Copy the code

Let’s see, this code, at first glance, looks good, but think about it, what if I add a shape? Like adding triangles. First, add a triangle class that inherits from Shape second, add a method that draws triangles drawTrriage() third, add a handler of type type=3 in draw. This violates the open closed principle – for extension development, closed for modification. One type was added and three code changes were made.

Let’s look at the right design

public class GraphicEditor1 {

    public void draw(Shape shape) {
        shape.draw();
    }



    interface Shape {
        void draw(a);
    }

    class Rectangle implements Shape {

        @Override
        public void draw(a) {
            System.out.println("Draw a rectangle."); }}class Circle implements Shape {

        @Override
        public void draw(a) {
            System.out.println("Draw circles"); }}}Copy the code

The various types of shapes regulate their own behavior, and graphicEditor.draw () is only responsible for drawing. When adding a type triangle. Just add a triangle class, implement Shape, and call Draw.

The entire process is an extension, without modifying the original class. This design is in accordance with the open and closed principle.

Case 2:

For example, now there is a banking service, saving money, withdrawing money and transferring money. What do we initially think?

  1. First, there is a banking class, which handles the banking business
  2. What does a bank do? Depositing money, withdrawing money, transferring money, these are all operations performed by banks
  3. So the outside says I’m going to deposit, I’m going to withdraw, I’m going to transfer, telling us by a type

The code is generated

package com.lxl.www.designPatterns.sixPrinciple.openclosePrinciple.bank;

/** * banking */
public class BankBusiness {

   public void operate(int type) {
       if (type == 1) {
           save();
       } else if(type == 2) {
           take();
       } else if(type == 3) { transfer(); }}public void save(a){
       System.out.println("Save");
   }

   public void take(a){
       System.out.println("Withdraw money");
   }

   public void transfer(a) {
       System.out.println("Transfer"); }}Copy the code

At first glance, the requirements have been met. But now there is a new need for banks to add functions-wealth management. Financial management is a kind of banking business, naturally is a new method. Then add a type to the operate() method. This is bad design, adding new functionality but changing the original code

We designed it to be an interface abstraction

public interface Business {
    public void operate(a);
}

public class Save implements Business{
    @Override
    public void operate(a) {
        System.out.println("Savings service"); }}public class Take implements Business {
    @Override
    public void operate(a) {
        System.out.println("Withdrawal service"); }}public class Transfer implements Business {
    @Override
    public void operate(a) {
        System.out.println("Transfer service"); }}/**
 * 银行业务类
 */
public class BankBusinesses {
    /** * Handle banking business *@param business
     */
    public void operate(Business business) {
        System.out.println("Dealing with banking."); business.operate(); }}Copy the code

Through the form of interface abstraction to facilitate expansion, to add new financial functions. Only need to add a financial class, other business code does not need to change.

In fact, in the daily work, often encountered this situation. Because we usually write more business logic, and business is like a ledger, today and tomorrow, bit by bit increase. So, when the business increases to 3, we need to think, how to write to facilitate the expansion of J

3.3 Thinking about reply link

Answer link includes pull the topic — – > initialization — — > the answer — — > corrections — — > > add integral corrects the subjective topic grade — > subjective topic back process, etc. So can such a link standardize code through the form of interface abstraction, to achieve the open and close principle? Without adding a type later, you need to add a new method. Actually, I think so.

Iv. Summary:

  1. Following the open – close principle can improve software scalability and maintainability.
  2. Most design patterns and design principles implement the open close principle.