设计格局,轻易工厂形式

日益的做笔录,做最有力的协和

  简单工厂方式(Factory
Pattern卡塔尔国是风姿浪漫种创制型的设计格局,像工厂同样基于须要分娩目的实例。

看了牛皮设计格局之后感触很深,发现自身还应该有多数学学的东西,设计软件并不是生机勃勃两句代码把成效写完了就能够,需求考虑的内容有成都百货上千

  特点:依照差别的法规,工厂实例化出相符的靶子。

代码来源仿照效法大话设计方式那本书,这里在博客里记录一下,不容许每一遍都去翻书,但是在博客里面是那个好找的。

  《大话设计形式》中实例:四则运臆度算器

楷模为贰个粗略工厂方式的总括器,首先先创建多少个计算器运算所必要动用的数据模型,在java内部也叫bean,正是多少个抽象的类,这里大家先创设一个Operation类

  代码:

public class Operation
    {
        private double _numberA = 0;
        private double _numberB = 0;

        public double NumberA
        {
            get { return _numberA; }
            set { _numberA = value; }
        }

        public double NumberB
        {
            get { return _numberB; }
            set { _numberB = value; }
        }

        public virtual double GetResult()
        {
            double results = 0;
            return results;
        }



    }
 1 #!/usr/bin/env python
 2 #-*- coding: utf-8 -*-
 3 
 4 class Operation:
 5     def getResult(self):
 6         pass
 7 
 8 class OperationAdd(Operation):
 9     def getResult(self):
10         return self.op1+self.op2
11 
12 class OperationSub(Operation):
13     def getResult(self):
14         return self.op1-self.op2
15     
16 class OperationMul(Operation):
17     def getResult(slef):
18         return self.op1*self.op2
19 
20 class OperationDiv(Operation):
21     def getResult(self):
22         try:
23             return self.op1/float(self.op2)
24         except:
25             print("Error:除数为0!")
26             return 0
27 
28 class OperationOther(Operation):
29     def getResult(self):
30         print("Error:没有定义的运算符!")
31         return 0
32     
33 
34 class OperationFactory:
35     
36     operation = {}
37     operation["+"] = OperationAdd()
38     operation["-"] = OperationSub()
39     operation["*"] = OperationMul()
40     operation["/"] = OperationDiv()
41     
42     def createOperation(self,choice):
43         if choice in self.operation.keys():
44             op = self.operation[choice]
45         else:
46             op = OperationOther()
47         return op
48 
49 
50 
51 if __name__ == "__main__":
52     op = raw_input("请输入运算符:")
53     num_a = input("a:")
54     num_b = input("b:")
55 
56     factory = OperationFactory()
57     cal = factory.createOperation(op)
58 
59     cal.op1 = num_a
60     cal.op2 = num_b
61     
62     print(u"运算结果为:" + str(cal.getResult()))
63 

下一场再成立加减乘除类,以便工厂进行调用

  

class OperationAdd : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA + NumberB;
            return result;
        }
    }

    class OperationSub : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA - NumberB;
            return result;
        }
    }

    class OperationMul : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA * NumberB;
            return result;
        }
    }

    class OperationDiv : Operation
    {
        public override double GetResult()
        {
            double result = 0;
            result = NumberA / NumberB;
            return result;
        }
    }

  当须求运用到单个实体的八个变体时,能够运用工厂形式。举个例子地点的例证中,要求做运算(单个实体卡塔 尔(英语:State of Qatar),可是常用的运算包括加、减、乘、除(变体卡塔尔,分歧的原则下需求创建差异的变体,这时候就能够通过工厂来创制分歧的演算。

创办工厂类,实例化出符合的指标

  步骤:

 public static Operation CreateOperate(string operate)
        {
            Operation oper = null;
            switch (operate)
            {
                case "+":
                    oper = new OperationAdd();
                    break;
                case "-":
                    oper = new OperationSub();
                    break;
                case "*":
                    oper = new OperationMul();
                    break;
                case "/":
                    oper = new OperationDiv();
                    break;

            }
            return oper;
        }
  • 创造实体类

    class Entity(): #实体

    def Func(self):
        "方法体"
    

         #pass

  • 成立变体类

    class Variant1(Entity):

    def Func(self):
    

         pass

 

class Variant2(Entity):
    def Func(self):
     pass

透过多态,重回父类的办法,然后完成计算结果

 

static void Main(string[] args)
        {
            Operation oper;
            oper = OperationFactory.CreateOperate("+");
            oper.NumberA = 1;
            oper.NumberB = 2;
            double result = oper.GetResult();
            Console.WriteLine(result);
            Console.ReadLine();
        }
  • 创制工厂类

    class EntityFactory():

    def create_variant(self,choice):
        #根据choice创建不同的variant类
        #函数体
        #return
    

可是轻易工厂方式会存在二个标题,后续假设新添方法的话那么还亟需后续创制运算类,然后实例化对象,那么这么会加多代码结构的复杂度,当然照旧有艺术消除的,但是此间就只做简单工厂格局的介绍了,

 

三层模型基本上只要不是用了特地的艺术那么基本都以基于轻易工厂格局来拍卖方法的

  使用工厂类:

  

factory  = EntityFactory()
variant = factory.create_variant(choice)
print(variant.Func())