Open/Closed principle

Source: Internet
Author: User
Tags abstract closure inheritance reflection
The Open closure principle (Ocp,open Closed Principle) is the core of all object-oriented principles. The goal of software design itself is to package change and reduce coupling, and the open closure principle is the most direct embodiment of this goal. Other design principles, many times to achieve this goal, such as the Liskov substitution principle to achieve the best, right inheritance level, can guarantee that the open closure principle will not be violated.
On the principle of open closure, the core idea is:
Software entities should be extensible and non-modifiable. In other words, the extension is open, and the modification is closed.
Therefore, the principle of open closure is mainly embodied in two aspects:
Opening up to extensions means that existing code can be extended to accommodate new situations when there are new requirements or changes.
Enclosing a modification means that once the class is designed, it can do its work independently, rather than making any modifications to the class.
"Demand always changes", "No software in the world is constant", these statements are the most classical expression of software requirements. A key point of transmission is that for software designers, it is necessary to achieve flexible system expansion without the need to modify the original system. And how can this be done.
Only dependent on abstraction. The core idea of open closure is to abstract programming, not specific programming, because the abstraction is relatively stable. Let the class depend on the fixed abstraction, so the modification is closed, but through the object-oriented inheritance and the polymorphism mechanism, can realize the inheritance of the abstract body, by covering its methods to change the inherent behavior, to implement a new extension method, so for the extension is open. This is the basic idea of implementing the principle of open closure, which is based on two basic design principles, which is the principle of Liskov substitution and synthesis/aggregation reuse. With regard to these two principles, we have a corresponding discussion in the other parts of this book, which will be discussed in depth in the Application Reflection section.
For classes that violate this principle, refactoring is required to improve, and the design patterns commonly used to implement are the template method mode and the strategy mode. Package change is an important means to realize this principle, and encapsulate the state of change frequently as a class.
Application Reflection
Standing in the bank window anxiously waiting for the user, in the long front of the team appear helpless. So it is a matter of course to put this frustration on the head of the bank, because the management of the banking business is obviously inappropriate. Bank business personnel in the face of the influx of customer demand, in the queue waiting for the people are not only a demand, someone deposit, someone transfer, also someone to purchase funds, busy salesman back and forth in different needs of the shuttle, scrambling to find a variety of processing documents, computer system function modules are also in different requirements to switch back and forth, This is a helpless scene that happens inside and outside the bank window. And every time I face the unified queue of the station-to-station system, all for the front long waiting for the crowd and complain, from the role of carding bank clerk, in the management of their business is too many, the corresponding to the software design to achieve, you can use this poor design as shown in Figure 1.
According to the above design ideas, the bank clerk to deal with the work, is implemented in this way:
Class Busybankstaff
{
Private bankprocess Bankproc = new bankprocess ();
Define business operations for bank employees
public void handleprocess (client client)
{
Switch (client. ClientType)
{
Case "Deposit User":
Bankproc.deposit ();
Break
Case "Transfer User":
Bankproc.transfer ();
Break
Case "Withdrawal Account":
Bankproc.drawmoney ();
Break
}
}
}
This design and the actual banking business and similar, each busybankstaff ("Busy" salesman) to accept different customer requirements, a flurry of choice to deal with different operating procedures, just like the implementation of the example code in the switch rules, this passive choice caused a lot of time wasted , and it's easy to make mistakes in different processes. At the same time, it is even more serious that when new business is added, you have to modify the business method in bankprocess, while modifying switch to add new business, this way obviously destroys the original pattern, in terms of design principle, is open to the modification. With this design to cope with the changing banking business, the staff can only become busybankstaff. To analyze this rigid code, at least the following points are worth noting: the banking business is encapsulated in a class, violating the principle of single responsibility; when new business requirements occur, they must be implemented by modifying existing code, violating the open closure principle.
The only way to solve this problem is to apply the open closure principle: To open the extension, to modify the closure. We went back to the banking business to see: why these businesses can not be adapted to adjust it. Each salesman does not have to deal with the various business options, the deposit, withdrawal, transfer, foreign exchange and other different business sub-window, each clerk happy to focus on one or a few related business, it will be much easier. Comprehensive application of a single responsibility principle to comb the banking business process, the effective separation of responsibilities, and this still does not solve the problem of automatic processing of business, you can still smell the rigidity of the bad taste in the system diffuse.
Application development closure principle, can give us more harvest, first of all, the most likely expansion of the banking system to isolate the part to form a unified interface processing, in the banking system is the most likely to expand the factor is the increase or change of business functions. For the business process should be implemented as an extensible part, when there is a new function increase, do not need to re-comb the formed business interface, and then the whole system to do large processing action, then how to better realize the coupling degree and flexibility of the dual mechanism.
The answer is abstraction. The business function is abstracted as an interface, and when the salesman relies on the fixed abstraction, it is closed to the modification, and the new extension implementation is derived from the abstract body through the inheritance and polymorphic mechanism, which is the opening to the extension.
Based on the open closure principle, the new design ideas are shown in Figure 2.
Figure 2 Abstract-oriented design
In accordance with the above design, the details are expressed as:
Interface Ibankprocess
{
void Process ();
}
Then, on the isolated interface, the functionality is extended, such as the example of transforming a single function, with the following implementation:
By Bank by business classification
Class Depositprocess:ibankprocess
{
Ibankprocess Members
#region Ibankprocess Members
public void Process ()
{
Deposit management Business
throw new Exception ("The method or operation is not implemented.");
}
#endregion
}
Class Transferprocess:ibankprocess
{
Ibankprocess Members
#region Ibankprocess Members
public void Process ()
{
Transfer business
throw new Exception ("The method or operation is not implemented.");
}
#endregion
}
Class Drawmoneyprocess:ibankprocess
{
Ibankprocess Members
#region Ibankprocess Members
public void Process ()
{
Handling of withdrawal operations
throw new Exception ("The method or operation is not implemented.");
}
#endregion
}
This conversion of ideas, will make complex problems become simple and clear, so that the system accountability, everyone affordable. With the refactoring above, the bank staff becomes a easybankstaff ("Easy" organizer):
Class Easybankstaff
{
Private ibankprocess bankproc = null;
public void handleprocess (client client)
{
Bankproc = client. CreateProcess ();
Bankproc.process ();
}
}
The banking business can be implemented automatically like this:
Class Bankprocess
{
public static void Main ()
{
Easybankstaff Bankstaff = new Easybankstaff ();
Bankstaff.handleprocess (New Client ("Transfer user"));
}
}
You see, now everything has become relaxed, in a hurry the people who handle the business will not helpless in front of the long team, and the salesman also from the tedious and complicated labor freed out. When a new business grows, the bank manager doesn't have to worry about re-organizing the business process, you only need to implement the Ibankprocess interface for the new business, and the rest of the system will not be affected, and the customers who handle the new business will easily find the window to accept new business, as shown in Figure 5.
Figure 5 OCP-compliant design
The corresponding implementations are:
Class Fundprocess:ibankprocess
{
Ibankprocess Members
#region Ibankprocess Members
public void Process ()
{
Handling of Fund business
throw new Exception ("The method or operation is not implemented.");
}
#endregion
}
It can be seen that the new design adheres to the principle of open closure, which only needs to add a new function implementation class to the system when the demand increases, and all the original remains in a closed state, which is an open and closed design based on the abstract mechanism.
However, careful observation of the above implementation you will find a very deadly problem: how people find the business window they want to deal with, is it necessary for the bank to be a part of the manpower to divert. It is true, however, that at least the current design must be so, so the implementation is not a real business process, and the current "easy" bank clerk is not really "relaxed", and we ignore the most important part of the business system is the user. Currently, the user's definition is implemented as:
Class Client
{
private string ClientType;
Public Client (String clienttype)
{
ClientType = ClientType;
}
Public ibankprocess CreateProcess ()
{
Switch (ClientType)
{
Case "Deposit User":
return new depositprocess ();
Break
Case "Transfer User":
return new transferprocess ();
Break
Case "Withdrawal user":
return new drawmoneyprocess ();
Break
}
return null;
}
}
If you have a new business, you also have to add new processing options to the Long Branch statement, the bad taste of switch still makes everyone look sick, the banking business or at the expense of the customer's choice, can not provide a self-organizing customer search business window mechanism.
One of the design principles is to solve the above problems.
Rule recommendations
The principle of open closure is the most important design principle, the principle of Liskov substitution and the principle of synthetic/aggregation multiplexing provide the guarantee for the realization of open closure principle.
L can reconstruct by template method mode and strategy mode, and realize the design idea of closed modification and open extension.
The change of package is an important means to realize the principle of open closure, and it is generally encapsulated as an abstraction for the frequently changing state, such as the Ibankprocess interface in the banking business.
L REJECT the misuse of abstraction and only abstract the frequently changing parts, which can be obtained from the learning and application of design patterns.

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.