Prostitutes also play with OCP

Source: Internet
Author: User

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.

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.