Strategy -- rule Mode

Source: Internet
Author: User

I. Mode Overview
The Strategy pattern is similar to the state pattern in the external form, but it is somewhat different from the figure. The intention is to make these algorithms replace each other and provide a method to select the most appropriate algorithm.

Calculate personal income tax and corporate income tax

II.

According to the above UML, it is not difficult to see that there are three main roles in the Policy mode: Environment roles, abstract policy roles and specific policy roles.
Context Role: a reference that holds an abstract policy (Strategy) role. It is also called context.
Abstract Policy (Strategy) Role: This is an abstract role, usually implemented by an interface or an abstract class.
Concretestrategy: encapsulates algorithms and behaviors.

Iii. Code Implementation


Public interface itaxstrategy
{
Double calculate (double income );
}

Public class personaltaxstrategy: itaxstrategy
{
Public double calculate (double income)
{
Return income * 0.1;
}
}

Public class enterprisetaxstrategy: itaxstrategy
{
Public double calculate (double income)
{
Return income * 0.5;
}
}

Public class taxop
{
Private itaxstrategy m_strategy;
Public taxop (itaxstrategy strategy)
{
M_strategy = strategy;
}
Public double gettax (double income)
{
Return m_strategy.calculate (income );
}
}

Class Program
{
Static void main (string [] ARGs)
{
Taxop op = new taxop (New personaltaxstrategy ());
Console. writeline ("the personal tax is: {0}", op. gettax (1000 ));

Console. Read ();
}
}

 

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.