现在正在学习大话设计模式(Java版),学习之后想加深印象,将内部的设计模式用Python代码实现一下, 代码可能写得有些幼稚,希望有大佬能多多斧正。也希望能够帮助看到这篇博客的同学。如果代码内容有问题,请联系,希望共同进步呀!!!
# -*- coding:utf-8 -*-
"""
作者:bug君
日期:2023年 03月 16日
标题:用面向对象语言编写一个计算器控制台程序,要求输入两个数和运算符号,得到结果
作用:
一、理解工厂模式:
工厂模式是一种创建型设计模式,作为工厂,它所关心的是产品的产生,
也就是对象的创建,我们利用工厂来创建对象,而不必我们亲自创建对象,我们无需去理解如何创建对象,
只需要向工厂提出要求,让工厂去根据你的要求,给你生产你要的产品,给你相应的对象,这种模式便叫做工厂模式。
二.工厂模式的优点:
松耦合,对象的创建独立于类的实现 客户端无需了解创建对象的类,只需知道需要传递的接口,方法和参数
就能够创建所需要的对象
思路:本方法仅实现了四则运算,如需实现其他方法,可类似仿造 arithometer类 及其 子类操作方法
通过将计算器中的 计算方法名 封装在一个类中, 可以随便调用任意方法
"""
# 文件命名为calculate
class arithometer:
result = 0
def default(self):
raise Exception('四则运算中不包含该操作符')
def selectMethod(self, operate):
dic = { # 用字典的键值可以模拟 switch case
'+': addMethod,
'-': subMethod,
'*': mulMethod,
'/': divMethod
}
func = dic.get(operate, self.default)
return func
def setResult(self, a, operate, b):
method = self.selectMethod(operate) # 工厂模式的特性,通过内部自己创建合适的对象
return method(a, b)
def getResult(self):
# method = self.selectMethod(operate)
# method(a, b)
return self.result
class addMethod(arithometer):
def __init__(self, a, b):
self.result = a + b
class subMethod(arithometer):
def __init__(self, a, b):
self.result = a - b
class mulMethod(arithometer):
def __init__(self, a, b):
self.result = a * b
class divMethod(arithometer):
def __init__(self, a, b):
if b == 0:
raise ArithmeticError
self.result = a / b
if __name__ == '__main__':
a = arithometer().setResult(1, '+', 2)
# print(a.result)
print(a.getResult())
# -*- coding:utf-8 -*-
"""
作者:bug君
日期:2023年 03月 17日
标题:四则运算——工厂模式的另一表示,在子类中重写父类中的getResult方法
作用:
思路:
"""
class arithometer:
result = 0
def default(self):
raise Exception('四则运算中不包含该操作符')
def selectMethod(self, operate):
dic = { # 用字典的键值可以模拟 switch case
'+': addMethod,
'-': subMethod,
'*': mulMethod,
'/': divMethod
}
func = dic.get(operate, self.default)
return func
def setResult(self, operate):
method = self.selectMethod(operate)
return method()
def getResult(self, a, b):
# method = self.selectMethod(operate)
# method(a, b)
return self.result
class addMethod(arithometer):
def getResult(self, a, b):
return a + b
class subMethod(arithometer):
def getResult(self, a, b):
return a - b
class mulMethod(arithometer):
def getResult(self, a, b):
return a * b
class divMethod(arithometer):
def getResult(self, a, b):
if b == 0:
raise ArithmeticError
return a / b
if __name__ == '__main__':
a = arithometer().setResult('+')
# print(a.result)
print(a.getResult(1, 2))
# -*- coding:utf-8 -*-
"""
作者:bug君
日期:2023年 03月 16日
标题:测试计算机工厂
作用:
思路:
"""
import calculate
import calculate_2
numberA = int(input('请输入数字A:'))
strOperate = input('请输入运算符(+、-、*、/):')
numberB = int(input('请输入数字B:'))
# res = calculate_01.Operation().setResut(numberA, strOperate, numberB).getResult() # 直接一行表达
# print(res)
res = calculate.arithometer() # 适用于 calculate
print(res.setResult(numberA, strOperate, numberB).getResult())
res = calculate_2.arithometer().setResult(strOperate) # 适用于 calculate_2
print(res.getResult(numberA, numberB))