Object-Oriented Design Principle 2: open and closed Principle

Source: Internet
Author: User

Closed development principle(Open-Closed Principle OCP)

Software entities (classes, modules, functions etc) shocould open for extension, but close for modification.

What does it mean?

The so-called open and closed principle means that software entities should be extended for development and closed for modification. The open and closed principle is the core of all object-oriented principles. The goal of software design itself is to encapsulate changes and reduce coupling. The principle of openness and closure is the most direct embodiment of this goal.

The principle of opening and closing is mainly reflected in two aspects:

Open to expansion means that existing code can be expanded to adapt to new situations when there are new requirements or changes.

Closed modification means that once the class is designed, it can work independently, instead of making any changes to the class.

 

Why should we use the open and closed principle?

The demand for software is always changing, and none of the software in the world remains the same. Therefore, for software designers, they must not modify the original system, flexible system expansion.

 

How can we enable and disable scaling?

The core idea of implementing open and closed programming is to abstract programming, rather than specific programming, because abstraction is relatively stable. Classes depend on fixed abstractions, so modifications are closed. Through Object-oriented Inheritance and polymorphism mechanisms, classes can inherit abstract bodies, by overwriting its methods to change the inherent behavior and implement new expansion methods, it is open to expansion.

Classes that violate this principle must be improved through refactoring. The design patterns commonly used for implementation mainly include the Template Method mode and the Strategy Mode. Encapsulation changes are an important means to implement this principle and encapsulate the changing state into a class.

Take a bank clerk as an Example

The OCP design is not implemented:

Public class BankProcess

{// Deposit

Public void Deposite (){}

// Withdraw money

Public void Withdraw (){}

// Transfer

Public void Transfer (){}

}

Public class BankStaff

{

Private BankProcess bankpro = new BankProcess ();

Public void BankHandle (Client client)

{

Switch (client. Type)

{// Deposit

Case "deposite ":

Bankpro. Deposite ();

Break;

// Withdraw money

Case "withdraw ":

Bankpro. Withdraw ();

Break;

// Transfer

Case "transfer ":

Bankpro. Transfer ();

Break;

}

}

}

This design is obviously problematic. Currently, there are only three functions in the design: deposit, withdrawal and transfer. In the future, if the business is increased, such as the fund purchase function and financial management function, you must modify the BankProcess business class. By analyzing the above design, we cannot find that the business cannot be encapsulated in a class, which violates the principle of single responsibility. However, if there is a new demand, modifying the existing Code violates the open and closed principle.

From the perspective of openness and closures, the most likely expansion in the banking system is the increase or change of business functions. The business process should be implemented as an extension part. When new functions are available, you do not need to reorganize existing services, and then make major changes to the system.

How can we achieve both coupling and flexibility?

That is, abstraction. business functions are abstracted as interfaces. When a clerk is dependent on a fixed abstraction, modification is closed, and inheritance and polymorphism inheritance are used, new implementations are extended from the abstract body, which is open to extensions.

The OCP-compliant design is as follows:

First, declare a service processing interface.

Public interface IBankProcess {void Process ();}

Public class DepositProcess: IBankProcess

{

Public void Process ()

{// Handle the deposit business

Console. WriteLine ("Process Deposit ");

}

}

Public class WithDrawProcess: IBankProcess

{

Public void Process ()

{// Handle withdrawal operations

Console. WriteLine ("Process WithDraw ");

}

}

Public class TransferProcess: IBankProcess

{

Public void Process ()

{// Handle the transfer business

Console. WriteLine ("Process Transfer ");

}

}

Public class BankStaff

{

Private IBankProcess bankpro = null;

Public void BankHandle (Client client)

{

Switch (client. Type)

{// Deposit

Case "Deposit ":

UserProc = new DepositUser ();

Break;

// Transfer

Case "Transfer ":

UserProc = new TransferUser ();

Break;

// Withdraw money

Case "WithDraw ":

UserProc = new WithDrawUser ();

Break;

}

UserProc. Process ();

}

}

 

In this way, when the business changes, you only need to modify the corresponding business implementation class, and other irrelevant businesses do not have to be modified. When the business increases, you only need to increase the business implementation.

 

Design Recommendations:

The principle of open and closed is the most important design principle. The principle of Liskov replacement and the principle of synthesis/aggregation reuse provide a guarantee for the principle of open and closed.

You can reconstruct the Template Method mode and Strategy Mode to implement the design idea of closed modification and open extension.

Encapsulation of changes is an important means to implement the open and closed principle. For the status that often changes, it is generally encapsulated into an abstract, such as the IBankProcess interface in the banking business.

Refuse to abuse abstraction and only abstract the frequently changed parts.

 

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.