简单工厂模式(Simple Factory Pattern)是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类.

例:

使用Python设计一个控制台计算器,要求输入两个数和运算符号,得到运算结果。

1. 初学者写法

class Operation(object):

    def __init__(self):
pass def conver_strNumber(self, strNumber):
'''
将字符串格式的数字,转化成对应格式的数字
:param strNumber:
:return:
'''
if '.' not in strNumber:
return int(strNumber)
else:
return float(strNumber) def op(self, strNumberA, strNumberB, strOperate):
if strOperate == '+':
return self.conver_strNumber(strNumberA) + self.conver_strNumber(strNumberB)
elif strOperate == '-':
return self.conver_strNumber(strNumberA) - self.conver_strNumber(strNumberB)
elif strOperate == '*':
return self.conver_strNumber(strNumberA) * self.conver_strNumber(strNumberB)
elif strOperate == '/':
if strNumberB != '0' and strNumberB != '0.0':
return self.conver_strNumber(strNumberA) / self.conver_strNumber(strNumberB)
else:
return 0
else:
print('只能做加减乘除运算') if __name__ == '__main__':
p = Operation()
print(p.op('2.2', '1', '+')) # 输出
21.2

分析:以上这种写法,将加减乘除运算全部放在一个类中实现,虽然实现了计算器的功能,但增加其他运算或修改某个运算都必须在Operation类中进行修改。 使得程序不容易维护、扩展以及复用,并且耦合性高

2.使用简单工厂模式

# Operation运算类
class Operation(object):
def __init__(self, strNumberA=0, strNumberB=0):
self.NumberA = strNumberA
self.NumberB = strNumberB def conver_strNumber(self, strNumber):
'''
将字符串格式的数字,转化成对应格式的数字
:param strNumber:
:return:
'''
if '.' not in strNumber:
return int(strNumber)
else:
return float(strNumber) def GetResult(self):
pass # 加法运算类
class OperationAdd(Operation):
def GetResult(self):
return self.conver_strNumber(self.NumberA) + self.conver_strNumber(self.NumberB) # 减法运算类
class OperationSub(Operation):
def GetResult(self):
return self.conver_strNumber(self.NumberA) - self.conver_strNumber(self.NumberB) # 乘法运算类
class OperationMul(Operation):
def GetResult(self):
return self.conver_strNumber(self.NumberA) * self.conver_strNumber(self.NumberB) # 除法运算类
class OperationDiv(Operation):
def GetResult(self):
if self.NumberB != 0 and self.NumberB != 0.0:
return self.conver_strNumber(self.NumberA) / self.conver_strNumber(self.NumberB)
else:
return '除数不能为0' # 其他操作符运算
class OperationUndef(Operation):
def GetResult(self):
return '操作符错误' # 简单工厂类
class OperationFactory(object):
def createOperate(self, operate):
if operate == '+':
return OperationAdd()
elif operate == '-':
return OperationSub()
elif operate == '*':
return OperationMul()
elif operate == '/':
return OperationDiv()
else:
return OperationUndef() if __name__ == '__main__': strNumA = '1.0'
strNumB = '2'
oper = '/' OP = OperationFactory()
oper_obj = OP.createOperate(oper)
oper_obj.NumberA = strNumA
oper_obj.NumberB = strNumB
result = oper_obj.GetResult()
print(result) # 输出
0.5

分析:将各种运算拆分成单独的类,均继承于Operation类,各运算子类重写Operation类中的GetResult()方法。统一通过简单工厂类(OperationFactory类)实例化运算所需的运算子类。

这样设计的优点:

  • 易扩展

    如果添加新的运算类,只需要

    1. 新的运算类继承Operation类,并重写GetResult()方法
    2. 在简单工厂类(OperationFactory类)中添加对应的if语句

    无需对其他运算类进行操作。

  • 易维护

    对某一运算类进行修改,并不涉及其他运算类,很大程度上避免了由于误操作而对其他运算类修改的问题。

  • 低耦合

    各运算类只公共继承Operation类,不涉及其他运算类。

  • 高复用

    无论是控制台,还是windows程序,Web程序,均可使用该程序实现计算器功能。


如果对您有用,欢迎扫描下方二维码关注公众号,会持续输出原创精彩文章,与您一起深入学习Python中好用、好玩的知识。

《大话设计模式》——简单工厂模式(Python版)的更多相关文章

  1. 负载均衡算法,轮询方式 大话设计模式之工厂模式 C#

    负载均衡算法,轮询方式 2018-04-13 17:37 by 天才卧龙, 13 阅读, 0 评论, 收藏, 编辑 学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现 ...

  2. 3. 星际争霸之php设计模式--简单工厂模式

    题记==============================================================================本php设计模式专辑来源于博客(jymo ...

  3. Golang设计模式—简单工厂模式(Simple Factory Pattern)

    Golang设计模式--简单工厂模式 背景 假设我们在做一款小型翻译软件,软件可以将德语.英语.日语都翻译成目标中文,并显示在前端. 思路 我们会有三个具体的语言翻译结构体,或许以后还有更多,但现在分 ...

  4. Python 设计模式--简单工厂模式

    简单工厂模式(Factory Pattern)是一种创建型的设计模式,像工厂一样根据要求生产对象实例. 特点:根据不同的条件,工厂实例化出合适的对象. <大话设计模式>中实例:四则运算计算 ...

  5. linkin大话设计模式--简单工厂

    linkin大话设计模式--工厂方法 什么是工厂方法:将多个类对象交给工厂来生成的设计被称为简单工厂模式,个人认为主要是为了实现解耦,在代码重构的时候会很重要. 代码如下: public class ...

  6. 大话设计模式之工厂模式 C#

    学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 大话设计模式一书中第一个开讲的设计模式是简单工厂模式,关于简单工厂模式大家可参考鄙人的博客:代 ...

  7. C++设计模式——简单工厂模式

    简单工厂模式(Simple Factory Pattern) 介绍:简单工厂模式不能说是一个设计模式,说它是一种编程习惯可能更恰当些.因为它至少不是Gof23种设计模式之一.但它在实际的编程中经常被用 ...

  8. 深入浅出设计模式——简单工厂模式(Simple Factory)

    介绍简单工厂模式不能说是一个设计模式,说它是一种编程习惯可能更恰当些.因为它至少不是Gof23种设计模式之一.但它在实际的编程中经常被用到,而且思想也非常简单,可以说是工厂方法模式的一个引导,所以我想 ...

  9. C#设计模式--简单工厂模式

    简单工厂模式是属于创建型模式,但不属于23种GOF设计模式之一. 举一个例子:一个公司有不同的部门,客户根据需要打电话到不同的部门.客户相当于上端,不同部门相当于下端.不使用简单工厂模式来实现的例子如 ...

  10. 设计模式 | 简单工厂模式(static factory method)

    按理说应该把书全都看完一遍,再开始写博客比较科学,会有比较全面的认识. 但是既然都决定要按规律更新博客了,只能看完一个设计模式写一篇了. 也算是逼自己思考了,不是看完就过,至少得把代码自己都敲一遍. ...

随机推荐

  1. SCAU-1076 K尾相等数

    代码借鉴SCAU-OJ(感谢!!) 题目:1076 K尾相等数 时间限制:500MS  内存限制:65536K提交次数:251 通过次数:80 题型: 编程题   语言: G++;GCC   Desc ...

  2. 推荐几个不错的console调试技巧

    在我们的日常前端开发中,使用最频繁的莫过于使用console.log在浏览器的控制台中打印出我们需要调试的信息,但是大部分人可能跟之前的我一样,没有意识到其实console除了log方法以外,还有很多 ...

  3. JAVA中快速生成get与set

    快捷键 ctrl+Alt+S generate getters and setters

  4. day 25 方法和函数 反射

    特殊成员的补充: # __str__ class Foo(object): def __init__(self): pass def func(self): pass def __str__(self ...

  5. Python 网络爬虫程序详解

    #!/usr/bin/python #调用python from sys import argv #导入sys是导入python解释器和他环境相关的参数 from os import makedirs ...

  6. PHP开发中session无法获取和保存问题解决方法

    今天在程序设计中无法在session中获得内容,使用编辑器打开php.ini配置文件,在其中搜索"session.save_path", 把行中前面注释用的";" ...

  7. 安装nvm管理多版本nodejs

    1.简介(什么是nvm) Node Version Manager(node版本管理器),用它在机器上安装并维护管理多个Node的版本 2.nvm临时切换(临时切换版本,只在当前终端内有效,新开终端无 ...

  8. VUE+DRF系列

    vue基础系列 001 路飞学诚项目简介 002 Vue简介 003 Vue引入 004 文本指令 005 事件指令 006 斗篷指令 007 属性指令 008 表单指令 009 条件指令 010 路 ...

  9. 高并发编程-CountDownLatch深入解析

    要点解说 CountDownLatch允许一个或者多个线程一直等待,直到一组其它操作执行完成.在使用CountDownLatch时,需要指定一个整数值,此值是线程将要等待的操作数.当某个线程为了要执行 ...

  10. RestTemplate 中文乱码

    @Configuration public class RestTemplateWithoutLoadBalance { @Bean("normalRestTemplate") p ...