The understanding of policy patterns: When a business has multiple requirements, at some point you need to use different methods to compute the results. At this time different ways can be understood as different strategies to solve the same problem. For example: Shopping malls cashier system calculation price, 1: Normal calculation 2: Merchandise discount calculation, 3: Full 300 minus 100 and other ways. You can handle requirements in three different strategies.
Simply put: The strategy pattern is used to encapsulate the algorithm, but in practice we find that it can be used to encapsulate almost any type of rule, as long as the analysis process to hear the need to apply different business rules at different times, we can consider using the policy model to deal with the possibility of this change.
Copy Code code as follows:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Threading.Tasks;
Namespace Designmodel
{
<summary>
Policy mode
</summary>
public class Tacticsmodel
{
public string type {get; set;}
Public virtual string GetResult ()
{
Return "";
}
}
public class Normal:tacticsmodel
{
public override string GetResult ()
{
Return "normal calculated price";
}
}
public class Discount:tacticsmodel
{
public override string GetResult ()
{
Return "at discounted prices";
}
}
public class Preferential:tacticsmodel
{
public override string GetResult ()
{
Return "full 300 minus 100 activities";
}
}
public class Cashcontext
{
Tacticsmodel TM = null;
Public Cashcontext (String type)
{
Switch (type)
{
Case "1":
TM = new Normal ();
Break
Case "2":
TM = new Discount ();
Break
Case "3":
TM = new Preferential ();
Break
Default
Break
}
}
public string GetResult ()
{
Return TM. GetResult ();
}
}
}
This approach is similar to a simple factory approach, but slightly different. The simple factory pattern needs to be leaked to the client two classes, the simple combination of a policy pattern and a factory model only leaks a Cashcontext class
Client Invoke Code:
Copy Code code as follows:
Console.WriteLine ("Please calculate type 1 normal, 2 discount, 3 discount:");
String type = Console.ReadLine ();
Cashcontext cc = new Cashcontext (type);
Console.WriteLine (CC. GetResult ());
Results:
It is still using the Swich, that is to say, adding a need to change the Swith statement, is very uncomfortable, but any changes in demand are required cost.
There is a difference between the level of cost. This place will have a better effect with reflective technology. Follow-up will be added.