您的位置:首页 > 编程语言 > Python开发

python设计模式(一)--简单工厂(上)

2016-05-10 00:00 726 查看
摘要: 交互式计算器代码, 继承、多态

最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:

书籍<<大话设计模式>> 第一章

Python 3.x

[code=plain]# -.- 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 NotImplementedError

class Add(Operation):

"""加法类"""

def get_result(self):
return self.x + self.y

class Subtract(Operation):

"""减法类"""

def get_result(self):
return self.x - self.y

class Multiply(Operation):

"""乘法类"""

def get_result(self):
return self.x * self.y

class Divide(Operation):

"""除法类"""

def get_result(self):
if self.y == 0:
raise ZeroDivisionError("除数不能为0!")
return self.x / self.y

class 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())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: