Introduction to OCP (OCP-open-closed principle)

Source: Internet
Author: User
Introduction to OCP (OCP -- open-closed principle ):

Software entities (classes, modules, functions, etc.) shocould be open for extension, but closed for modification. The software entity should be open to the extension and closed to the modification, that is, the software entity should be extended without modification (which may be achieved through the proxy mode in. net. Open for extension: when new requirements arise, you can expand the existing model to achieve the goal. Close for modification: you cannot modify existing binary code, such as DLL and jar. Ii. OCP example: 1. Example 1If we want to write a payroll tax, which has different calculation rules in different countries, if we do not stick to OCP, We will directly write a tax calculation method that encapsulates the payroll tax, the specific implementation details of wage tax vary with different countries! If we allow modification, that is to say, we put all the wage taxes (Chinese wage taxes, U.S. wage taxes, etc.) required by the current system in one category, no one can guarantee that the system will not be sold to Japan in the future, once there is a new payroll tax, and this kind of payroll tax must be implemented in software, what we can do at this time is to find this kind of file, add the Implementation Details of Japanese tax to each method and recompile them into DLL! Although in. in the running environment of net, we only need to overwrite the new DLL to the original DLL, without affecting the normal operation of the existing program, but every time a new situation occurs, we need to find the class file, adding new implementation details makes it increasingly difficult to maintain such files and does not meet the single responsibility principle (SRP) We previously mentioned ), because wage tax changes in different countries will lead to motivation for such changes! If we stick to the OCP when designing this class, we will abstract the common method of payroll tax into an interface, closed the modification, and on the client (Class Object using this interface) we only rely on this interface to implement the payroll tax we need. If the system needs to add a new payroll tax in the future, we only need to extend the payroll tax of a specific country to implement the previously defined interface, you do not have to modify the original class file!   2. Example 2The example below is neither open nor closed, because the client and server are specific classes, if you want the client to use a different server class, you need to modify all the server classes in the client class to the new server class. Class Client
{
Server server;
Void getmessage ()
{
Server. Message ();
}
} Class Server
{
Void message ();
} The following is an implementation that complies with the OCP principle after modification. We can see that the server class inherits from the clientinterface, but the clientinterface is not called the serverinterface, the reason is that we want the clientinterface to be fixed for the client, and only the server is changed. This actually turns into a policy mode (gof Strategy) interface clientinterface
{
Public void message ();
// Other functions
} Class server: clientinterface
{
Public void message ();
} Class client
{
Clientinterface ci;
Public void getmessage ()
{
CI. Message ();
}
Public void client (clientinterface paramci)
{
Ci = paramci;
}
} // In the main function (or the main control side ),
Public static void main ()
{
Clientinterface CI = new server ();
// If there is a new server class above, you only need to replace server.
Client client = new client (CI );
Client. getmessage ();
} 3. Example 3Use template method to implement OCP: public abstract class policy
{
Private int [] I = {1, 1234,123 4, 1234,132 };
Public bool sort ()
{
Soribd ();
}
Protected virtual bool soribd ()
{}
} Class bubbleimp: Policy
{
Protected override bool soribd ()
{
// Bubble sort
}
}
Class bintreeimp: Policy
{
Protected override bool soribd ()
{
// Binary sorting
}
} // Implement static void main (string [] ARGs) in the main function)
{
// If you want to use Bubble sorting, change the following bintreeimp to bubbleimp.
Policy sort = new bintreeimp ();
Sort. Sort ();
} Iii. Advantages of OCP:1. Reduce the coupling between various parts of the program and make it possible to swap program modules;
2. Facilitate unit testing for each part of the software. By compiling a simulation class (Mock) consistent with the interface, it is easy to implement unit testing for each part of the software;
3. facilitate the call of software modules. During software upgrade, only the changed parts can be deployed without affecting other parts; 4. OCP usage notes:1. The key to implementing the OCP principle is abstraction. 2. The two safe design patterns for implementing the open and closed principles are strategy pattern and template methord ); 3. Based on the open/closed principle, we should try not to modify the class and only extend the class. However, in some cases, some strange situations may occur. In this case, we can combine several classes to complete the operation; 4. encapsulate the parts that may change into an object, such as status, message, algorithm, and data structure. encapsulation change is an important means to implement the "open/closed principle, such status values that change frequently, such as temperature, pressure, color, points, and rankings, can be used as independent attributes. If there is a relationship between parameters, it is necessary to abstract them. For behavior, if it remains unchanged, it can be directly used as an object method. Otherwise, consider abstracting or encapsulating these behaviors. 5. In many aspects, OCP is the core of object-oriented design. Following this principle can bring about the great benefits that object-oriented technology claims (flexibility, reusability, and maintainability ). However, it is not a good idea to abstract every part of an application. We should only abstract the part that shows frequent changes in the program. Rejecting immature abstraction is as important as abstraction itself;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.