看了《大话设计模式》后,深有体会,看着大婶们一个个的在搞设计模式,对于程序猿,这样的基础还是需要打打的,下面是菜鸟我用工厂模式写的python代码,不管好与劣,权且记录下来再说吧,留待以后自己万一哪天成大神后再来嘲笑自己。
#!/usr/bin/python # coding: utf-8 class Coding(object): """处理编码问题""" def __init__(self, str_a, de_code, en_code): self.str_a = str_a self.de_code = de_code self.en_code = en_code def return_value(self): return self.str_a.decode(self.de_code).encode(self.en_code) class SuperClass(object): """一个超级运算符类,用来继承 """ def __init__(self, a, b): pass def return_value(self): pass class Main(object): """显示主界面""" def __init__(self): print Coding(‘----------------------‘, ‘utf-8‘, ‘gb2312‘).return_value() print Coding(‘* 计算器 *‘, ‘utf-8‘, ‘gb2312‘).return_value() print Coding(‘----------------------‘, ‘utf-8‘, ‘gb2312‘).return_value() def get_value_a(self): self.a = raw_input(Coding(‘左操作数>‘, ‘utf-8‘, ‘gb2312‘).return_value()) def get_value_b(self): self.b = raw_input(Coding(‘右操作数>‘, ‘utf-8‘, ‘gb2312‘).return_value()) def get_operation(self): self.operation = raw_input(Coding(‘操作符>‘, ‘utf-8‘, ‘gb2312‘).return_value()) def return_result(self): return (self.a, self.b, self.operation) class Add(SuperClass): """加运算""" def __init__(self, a, b): self.a = int(a) self.b = int(b) def return_value(self): return self.a+self.b class Minus(SuperClass): """减运算""" def __init__(self, a, b): self.a = int(a) self.b = int(b) def return_value(self): return self.a-self.b class Multi(SuperClass): """乘法运算""" def __init__(self, a, b): self.a = int(a) self.b = int(b) def return_value(self): return self.a*self.b class Div(SuperClass): """除法运算""" def __init__(self, a, b): self.a = int(a) self.b = int(b) def return_value(self): return self.a/self.b class Factory_calcu(object): """对象工厂类""" def __init__(self, cal, a, b): self.cal = cal def return_value(self): cal_obj = self.cal(a, b) return cal_obj operation_dic = {‘+‘:Add, ‘-‘:Minus, ‘*‘:Multi, ‘/‘:Div} if __name__ == ‘__main__‘: main = Main() main.get_value_a() main.get_value_b() main.get_operation() a, b, operation = main.return_result() a = Coding(a, ‘gb2312‘, ‘utf-8‘).return_value() b = Coding(b, ‘gb2312‘, ‘utf-8‘).return_value() operation = Coding(operation, ‘gb2312‘, ‘utf-8‘).return_value() operation_obj = Factory_calcu(operation_dic[operation], a, b).return_value() print Coding(‘计算结果为:‘, ‘utf-8‘, ‘gb2312‘).return_value() print operation_obj.return_value()