zoukankan      html  css  js  c++  java
  • Python 设计模式--简单工厂模式

      简单工厂模式(Factory Pattern)是一种创建型的设计模式,像工厂一样根据要求生产对象实例。

      特点:根据不同的条件,工厂实例化出合适的对象。

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

      代码:

     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 Entity():     #实体
        def Func(self):
            "方法体"
         #pass
    • 创建变体类
    class Variant1(Entity):
        def Func(self):
         pass
    class Variant2(Entity): def Func(self):
         pass
    • 创建工厂类
    class EntityFactory():
        def create_variant(self,choice):
            #根据choice创建不同的variant类
            #函数体
            #return
            

      使用工厂类:

      

    factory  = EntityFactory()
    variant = factory.create_variant(choice)
    print(variant.Func())
  • 相关阅读:
    PL/SQL 入门
    Nginx 安装和配置
    MySql 优化方案
    类加载器(ClassLoader)
    动态代理入门
    Servlet 3.0 介绍
    反射加强(一)
    Python(1)—is和==区别
    代码题(10)— 验证二叉搜索树、二叉搜索树的最近公共祖先
    代码题(9)— 二叉树的最大、最小深度、平衡二叉树
  • 原文地址:https://www.cnblogs.com/cloudPython/p/4912583.html
Copyright © 2011-2022 走看看