1: OCP: open-closed Principle
* Open for extension
* Close for Modification
2: Case
Callet prostitutes are those who pull customers and receive sexual compensation. Let's divide the prostitutes by their positions. Prostitutes have different prices for different identities.
3: Design
Our general design is like this.
Class callet
{
Man man;
Public void getmoney ()
{
Man. Pay ();
}
}
Class man
{
Public void pay ()
{}
}
But now callet prostitutes have another customer in different positions, such as US President Bush. Then we will modify man's pay method. This is not in line with the OCP principles
We need to encapsulate the change point [hacker of different positions]. The key to encapsulation in OCP is abstraction [or interface ]. Now, we have a variety of positions
Abstract An abstract class Iman. The abstract method is pay
Public abstract class iMAN
{
Public abstract void pay ();
}
The President Class President inherits from iMAN
Public class presidentman: iMAN
{
Public override void pay ()
{
System. Console. writeline ("1234123.413 $ ");
}
}
It also inherits from Iman.
Public class itman: iMAN
{
Public override void pay ()
{
System. Console. writeline ("50.413 $ ");
}
}
public class callet
{< br> Iman _ Iman;
Public callet (Iman man)
{< br> This. _ Iman = man;
}< br> Public void getmoney ()
{< br> _ Iman. pay ();
}< BR >}
ClientProgram
Class app
{
Static void main ()
{
// The price of the prostitute and the hacker's president
Iman = new presidentman ();
Callet c = new callet (Iman );
System. Console. Write ("pre :");
C. getmoney ();
// It price of prostitutes and hackers
Iman = new itman ();
Callet C1 = new callet (Iman );
System. Console. Write ("it :");
C1.getmoney ();
System. Console. Readline ();
}
}
4: Conclusion
From the example above, we can see the benefits of OCP.