Home Java javaTutorial Detailed explanation of the open and closed principle in Java

Detailed explanation of the open and closed principle in Java

Aug 09, 2017 pm 02:10 PM
java in principle Detailed explanation

Definition: Software entities (classes, modules, functions, etc.) should be extensible but not modifyable. Open for expansion, closed for change. The key is abstraction, which clearly separates the general parts of a feature from the implementation details.

Here we are required to have abstract concepts when writing code. What is abstraction? Refers to the thinking process of abstracting concepts from entities. It is to extract common essential characteristics from numerous objects. In the process of writing code, where an abstract class is needed, you only need to grasp the essential function of this class, and don't always think about its specific function in this project.

Let’s continue to look at the open and closed principle. This principle requires that the shared part and the implementation part of a function be clearly separated. Because you cannot predict all the changes that will occur when you first build the architecture, then this class will not remain unchanged. As you implement it in each module, you will find that the abstract class is suitable for this function, but It is not suitable for another function. So do you want to go back and modify the abstract class? This cost is very high and requires re-thinking and adjusting specific details. It's better if the program hasn't been released yet. Once the program is released, going back to modify the abstract class will have a greater impact. Therefore, when starting to abstract, we must prevent this phenomenon from happening and follow the open and closed principle. Abstract classes and interfaces are standards. Once defined in a program, they cannot be easily modified. What should I do if the requirements change? You can extend this interface, rewrite methods, or add new methods after inheritance, but be sure not to modify it.

The following two examples are used to illustrate the open and closed principle.

1. Connect to the database as an example.

For example, the different types of database connections used in the program, Access and Oracle. The direct connection is as follows:


class ConnectAccess 
{ 
  public string ConnectString() 
  { 
    string dataPath = "数据库路径"; 
    return string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Persist Security Info=True;Jet OLEDB:Database Password={1}", dataPath, "密码"); 
  } 
} 
class ConnectOracle 
{ 
  public string ConnectString() 
  { 
    return @"server=localhost;database=命名空间;uid=用户名;pwd=密码"; 
  } 
}
Copy after login

Call


static void Main(string[] args) 
 { 
   //连接Access 
  ConnectAccess connAccess = new ConnectAccess(); 
 
  OleDbConnection accessConnection = new OleDbConnection(connAccessConnectString()); 
 
   //连接Oracle 
  ConnectOracle connOracle = new ConnectOracle(); 
 
  OracleConnection oracleConnection = new OracleConnection(connOracleConnectString()); 
 }
Copy after login

so you have to consider it every time Which parameters of OleDbConnection are used? Modify it below. Abstract an interface.


interface ConnectDataBase 
{ 
  string ConnectString(); 
} 
 
class ConnectAccess : ConnectDataBase 
{ 
  #region ConnectDataBase 成员 
 
  public string ConnectString() 
  { 
    string dataPath = "数据库路径"; 
 
    return stringFormat("Provider=MicrosoftJetOLEDB0;Data Source={0};Persist Security Info=True;Jet OLEDB:Database Password={1}", dataPath, "密码"); 
  } 
 
  #endregion 
} 
 
class ConnectOracle : ConnectDataBase 
{ 
  #region ConnectDataBase 成员 
 
  public string ConnectString() 
  { 
    return @"server=localhost;database=命名空间;uid=用户名;pwd=密码"; 
  } 
 
  #endregion 
}
Copy after login

Call


static void Main(string[] args) 
{ 
  ConnectDataBase conn = null; 
 
  //连接Access 
  conn = new ConnectAccess(); 
 
  OleDbConnection accessConnection = new OleDbConnection(connConnectString()); 
 
  //连接Oracle 
  conn = new ConnectOracle(); 
 
  OracleConnection oracleConnection = new OracleConnection(connConnectString()); 
}
Copy after login

After the change, you only need to care about which class conn uses Instantiate and that's it. However, you may see that since Oracle connection requires OracleConnection, the advantages may not be easy to see.

2. Take the basic type as a method parameter as an example.

This is the reason why general design principles emphasize that method parameters should avoid basic types as much as possible. Compare the following two method definitions:


//定义1  
bool Connect(string userName, string password, string wifiAddress, int port) 
{ 
  return false; 
}
Copy after login


//定义2  
bool Connect(Account account) 
{ 
  return false; 
}
Copy after login


public class Account 
{ 
  public string UserName 
  { 
    get; 
    set; 
  } 
  public string Password 
  { 
    get; 
    set; 
  } 
  public string WifiAddress 
  { 
    get; 
    set; 
  } 
  public int Port 
  { 
    get; 
    set; 
  } 
}
Copy after login

In comparison , Definition 2 has one more definition of Account class, and the Connect() method is obviously more stable. If the Connect() method wifiAddress changes, definition 1 must modify the interface of the method, and accordingly, all objects that call the Connect() method will be affected; while definition 2 only needs to modify the Account class, because the interface of the Connect() method remains remains unchanged, and the caller of the Connect() method does not need the wifiAddress. Such modification will not affect the caller at all, thereby reducing the impact of demand changes.

In short, the most important thing about the open and closed principle is abstraction, but it does not mean that once the abstract interface and class are determined, they must not be modified. However, when we are abstracting, we must think comprehensively and strive to avoid modification. Once the requirements change, we only need to make changes during implementation. Of course, the needs are ever-changing. Once the abstract part needs to be changed, as long as the principle is strictly followed, the impact will be much smaller. Of course, if it is modified, unit testing must be performed, and everything used must be tested correctly.

The above is the detailed content of Detailed explanation of the open and closed principle in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles