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 ();
}
}