最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第一章
Python 3.x
# -.- coding:utf-8 -.-# __author__ = 'zhengtong'# 简单工厂实现# 知识点:# 1. 继承(类后面加上基类Operation)# 2. 多态(每个子类都出现的get_result)# 编码过程:# 1. 当出现新的需求时,可以通过新增一个类来完成.# 2. 将新的类加入到工厂类的operators字典表中.class Operation: """运算类""" def __init__(self, x, y): self.x = int(x) self.y = int(y) def get_result(self): raise NotImplementedErrorclass Add(Operation): """加法类""" def get_result(self): return self.x + self.yclass Subtract(Operation): """减法类""" def get_result(self): return self.x - self.yclass Multiply(Operation): """乘法类""" def get_result(self): return self.x * self.yclass Divide(Operation): """除法类""" def get_result(self): if self.y == 0: raise ZeroDivisionError("除数不能为0!") return self.x / self.yclass SimpleFactory: """简单工厂""" @staticmethod def create_operate(operator, x, y): operators = {'+': Add, '-': Subtract, '*': Multiply, '/': Divide} if operator not in operators: raise KeyError('无效的操作符') return operators.get(operator)(x, y).get_result()def main(): """ 界面交互逻辑函数 """ x = int(input('请输入数字A:')) operator = input('请输入运算符号(+、-、*、/):') y = int(input('请输入数字B:')) return SimpleFactory.create_operate(operator, x, y)if __name__ == '__main__': print(main())