Design Patterns - Simple Factory

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 simFactory
{
        public static baseClass createBaseClass(string type)
        {
                swicth(type)
                {
                        case "我需要加法":return new A();
                        case "我需要减法":return new B();
                }
                return null;
        }
}

前端:
baseClass bc=simFactory.createBaseClass("我需要加法");
bc.getResult(1,2);

bc=simFactory.createBaseClass("我需要减法");
bc.getResult(2,3);

Design Patterns - Simple Factory
Summary: The simple factory pattern includes various business objects, the base class of business objects, and the core is the factory class. The factory class receives the new object according to the condition.
Advantages: The client does not need to pay attention to the business object, and only needs to pass its own wishes into the factory to get the corresponding object.
Disadvantage: more business and huge factory

Guess you like

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