Design Patterns - Strategy Patterns

public abstract class baseClass
{
        public abstract double getResult(double num1,double num2);
}
public class A:baseClass
{
        public overrid double getResult(double num1,double num2)
        {
                return num1+num2;
        }
}
public class B:baseClass
{
        public overrid double getResult(double num1,double num2)
        {
                return num1-num2;
        }
}

public class Context
{
       baseClass bc{get;set;}
       public Context(baseClass _bc)
             {
                         bc=_bc;
             }
             public double getResult(double num1,double num2)
             {
                         return bc.getResult(num1,num2);
             }
}

前端:
A a=new A();
Context c=new Context(a);
c.getResult(300,200);

Design Patterns - Strategy Patterns

Summary: The strategy mode requires the front-end to pass in specific business objects to the Context configuration class, and then obtain the required requirements through the getResult of the configuration class;
Advantages: Each business object can be replaced without affecting each other,
Disadvantage: The front-end needs to depend on too many objects.

The strategy pattern is similar to the factory pattern. The business objects are the same, except that the factory is the production object, and the strategy configuration class is the incoming object.

The combination of factories and strategies is better:

public class Context
{
       baseClass bc{get;set;}
       public Context(string type)
             {
                         swicth(type)
                         {
                            case “1”:bc=new A();
                                case “2”:bc=new B();
                         }
             }
             public double getResult(double num1,double num2)
             {
                         return bc.getResult(num1,num2);
             }
}
前端:
Context c=new Context(1“”);
c.getResult(300,200);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324915080&siteId=291194637