①工厂模式:只产生对象,不调用方法
工厂方法: 根据传入参数的不同, 而返回对应的不同对象
class TomatoesAndEgg: def __init__(self): self.data = "男士喜欢吃番茄炒蛋" def getData(self): return self.data class SugarAndCucumber: def __init__(self): self.data = "女士喜欢吃糖拌黄瓜" def getData(self): return self.data # 工厂方法: 根据传入参数的不同, 而返回对应的对象 def cook_factory(sex): if sex == "man": food = TomatoesAndEgg elif sex == "woman": food = SugarAndCucumber else: raise ValueError("请出入正确的性别: {}".format(sex)) return food() if __name__ == "__main__": man = cook_factory("man") woman = cook_factory("woman") data_man = man.getData() # 返回String类型数据 data_woman = woman.getData() # 返回int类型数据 # getData()返回不同类型的数据, 这在实际开发中是很常见的 print(data_man) # => 男士喜欢吃番茄炒蛋 print(data_woman) # => 女士喜欢吃糖拌黄瓜
C:UsersdellDesktop练习6>py -3 0613.py
男士喜欢吃番茄炒蛋
女士喜欢吃糖拌黄瓜
工厂模式与多态的区别?
def cook_factory(food):
return food() #工厂函数,只返回实例,不做调用
food().getData()#调用了实例的方法,多态
②抽象工厂模式
本质:调用工厂类的不同实例方法,产生不同实例的方式,叫做抽象工厂模式
class TomatoesAndEgg: def __init__(self): self.data = "番茄炒蛋" def getData(self): return self.data class SugarAndCucumber: def __init__(self): self.data = "糖拌黄瓜" def getData(self): return self.data # 厨子 # 抽象工厂(可以有多个), 有一组工厂方法, 每个工厂方法生产对应的对象 class CookFactory: # 生产'番茄炒蛋'的工厂方法 def cook_te(self): return TomatoesAndEgg() # 生产'白糖拌黄瓜'的工厂方法 def cook_sc(self): return SugarAndCucumber() if __name__ == "__main__": cook = CookFactory() man = cook.cook_te() woman = cook.cook_sc() data_man = man.getData() data_woman = woman.getData() print(data_man) # => 番茄炒蛋 print(data_woman) # => 白糖拌黄瓜
C:UsersdellDesktop练习6>py -3 0613.py
番茄炒蛋
糖拌黄瓜
③构建者模式
本质:用一个类,批量调用另外一个实例的所有方法,每一个动作和批量调用是分开定义的。
from abc import ABCMeta, abstractmethod class Builder(): __metaclass__ = ABCMeta @abstractmethod def draw_left_arm(self): pass @abstractmethod def draw_right_arm(self): pass @abstractmethod def draw_left_foot(self): pass @abstractmethod def draw_right_foot(self): pass @abstractmethod def draw_head(self): pass @abstractmethod def draw_body(self): pass class Thin(Builder): def draw_left_arm(self): print('画左手') def draw_right_arm(self): print('画右手') def draw_left_foot(self): print('画左脚') def draw_right_foot(self): print('画右脚') def draw_head(self): print('画头') def draw_body(self): print('画瘦身体') class Fat(Builder): def draw_left_arm(self): print('画左手') def draw_right_arm(self): print('画右手') def draw_left_foot(self): print('画左脚') def draw_right_foot(self): print('画右脚') def draw_head(self): print('画头') def draw_body(self): print('画胖身体') class Director(): def __init__(self, person): self.person=person def draw(self): self.person.draw_left_arm() self.person.draw_right_arm() self.person.draw_left_foot() self.person.draw_right_foot() self.person.draw_head() self.person.draw_body() if __name__=='__main__': thin=Thin() fat=Fat() director_thin=Director(thin) director_thin.draw() print("-"*30) director_fat=Director(fat) director_fat.draw()
C:UsersdellDesktop练习6>py -3 0613.py
画左手
画右手
画左脚
画右脚
画头
画瘦身体
------------------------------
画左手
画右手
画左脚
画右脚
画头
画胖身体
④设计模式
代理模式:把真正的对象隔开,代理可以在中间做一些其他的事情,
代理的好处:把真正实现的类隔开了,自己可以在中间干一些事
示例:
#encoding=utf-8 from abc import ABCMeta, abstractmethod class FemaleA(): def __init__(self, name): self.name = name class Male(): __metaclass__ = ABCMeta @abstractmethod def send_flower(self): pass @abstractmethod def send_chocolate(self): pass @abstractmethod def send_book(self): pass class MaleA(Male): def __init__(self, name, love_female): self.name = name self.love_female = FemaleA(love_female) def send_flower(self): print ('%s送花给%s' % (self.name, self.love_female.name)) def send_chocolate(self): print ('%s送巧克力给%s' % (self.name, self.love_female.name)) def send_book(self): print ('%s送书给%s' % (self.name, self.love_female.name)) class Proxy(Male): def __init__(self, name, proxyed_name, love_female): self.name = name self.proxyed = MaleA(proxyed_name, love_female) def send_flower(self): self.proxyed.send_flower() def send_chocolate(self): self.proxyed.send_chocolate() def send_book(self): self.proxyed.send_book() if __name__ == '__main__': p = Proxy('男B', '男A', '女A') p.send_book() p.send_chocolate() p.send_flower()
⑤状态代理
示例:
#encoding=utf-8 from abc import ABCMeta, abstractmethod class State(): __metaclass__ = ABCMeta @abstractmethod def write_code(self): pass class Morning(State): def write_code(self, work): if work.hour <= 12 and work.hour > 8: print('上午工作,精神百倍') else: print("Morning write_code is invoked!") work.set_status(Noon()) work.write_code(work) class Noon(State): def write_code(self, work): if work.hour <= 14 and work.hour>12 : print('中午工作,困,想午休') else: print("noon write_code is invoked!") work.set_status(Afternoon()) work.write_code(work) class Afternoon(State): def write_code(self, work): if work.hour <= 18 and work.hour>14: print('下午工作,状态不错') else: print("Afternoon write_code is invoked!") work.set_status(Eve()) work.write_code(work) class Eve(State): def write_code(self, work): if work.hour <= 22 and work.hour>18: print('加班了,状态不太好') else: print("Eve write_code is invoked!") work.set_status(Night()) work.write_code(work) class Night(State): def write_code(self, work): if work.hour <= 8 or work.hour > 22: print('不行了,要睡觉了') else: print("Night write_code is invoked!") work.set_status(Morning()) work.write_code(work) class Work(): def __init__(self, hour): self.hour = hour self.state = Morning() def set_status(self, state): self.state = state def write_code(self, work): self.state.write_code(work) if __name__ == '__main__': work = Work(10) for hour in (14,20): work.hour = hour print('%d点,' % hour) work.write_code(work)
⑥模板模式
示例:
#encoding=utf-8 #把打印的公共方法抽象到一个基类中,要用到的数据方法另外一个子类中 class Student(): def answer1(self): print('题目一:XXXXXX') print('我的答案是:%s' %self.get_answer1()) def get_answer1(self): pass def answer2(self): print('题目二:XXXXXX') print('我的答案是:%s' %self.get_answer2()) def get_answer2(self): pass class StudentA(Student): def get_answer1(self): return 'B' def get_answer2(self): return 'B' class StudentB(Student): def answer1(self): return 'C' def answer2(self): return 'D' if __name__=='__main__': student_a=StudentA() student_a.answer1() student_a.answer2() student_b=StudentB() student_b.answer1() student_b.answer2()
⑦命令模式
示例:
class Switch: ''' The INVOKER class:传令官''' def __init__(self, flipUpCmd, flipDownCmd): self.__flipUpCommand = flipUpCmd self.__flipDownCommand = flipDownCmd def flipUp(self):#传开灯的命令 self.__flipUpCommand.execute() def flipDown(self):#传关灯的命令 self.__flipDownCommand.execute() class Light: '''The RECEIVER Class:执行者''' def turnOn(self): print("The light is on") def turnOff(self): print("The light is off") class Command: """The Command Abstrace class""" def __init__(self): pass def execute(self): pass class FlipUpCommand(Command):#开灯传令的对象 '''The Command class for turning on the light''' def __init__(self, light): self.__light = light def execute(self): self.__light.turnOn() class FileDownCommand(Command):#关灯传令的对象 '''The Command class for turning off the light''' def __init__(self, light): Command.__init__(self) self.__light = light def execute(self): self.__light.turnOff() class LightSwitch: '''The Client Class:发起者''' def __init__(self): self.__lamp = Light() self.__switchUp = FlipUpCommand(self.__lamp) self.__switchDown = FileDownCommand(self.__lamp) self.__switch = Switch(self.__switchUp, self.__switchDown) def switch(self, cmd): cmd = cmd.strip().upper() try: if cmd == "ON": self.__switch.flipUp() elif cmd == "OFF": self.__switch.flipDown() else: print("Argument "ON" or "OFF" is required") except Exception as msg: print("Exception occured:%s" % msg) #Execute if the file is run as a script and not imported as a module if __name__ == "__main__": lightSwitch = LightSwitch() print("Switch ON test") lightSwitch.switch("ON") print("Switch OFF test") lightSwitch.switch("OFF") print("Invalid Command test") lightSwitch.switch("****")
⑧外观模式
本质:批量调用其他的类的逻辑被封装到了外观类的方法里。
示例:
#encoding=utf-8 class A(): def run(self): print('A run') def jump(self): print('A jump') class B(): def run(self): print('B run') def jump(self): print('B jump') class C(): def run(self): print('C run') def jump(self): print('C jump') class Facade(): def __init__(self): self.a=A() self.b=B() self.c=C() def run(self): #批量操作 for item in ('a','b','c'): getattr(self,item).run() def jump(self): for item in ('a','b','c'): getattr(self,item).jump() if __name__=='__main__': facade=Facade() facade.run() facade.jump()
⑨组合模式
示例:
def count_to(count): """Counts by word numbers, up to a maximum of five""" numbers= ["one","two", "three", "four","five"] #>>> list(zip(range(2), numbers)) #[(0, 'one'), (1, 'two')] #range中的数量可以限制产生几个number中的元素 for pos, number in zip(range(count), numbers): yield number # Test the generator count_to_two = lambda: count_to(2) count_to_five = lambda: count_to(5) print('Counting to two...') for number in count_to_two(): print (number) print(" ") print('Counting to five...') for number in count_to_five(): print (number)
⑩策略模式
示例:
import types #核心思想:将外部的函数,转化为类中的方法。 #改变类中的实现算法。 class StrategyExample: def __init__(self, func=None): self.name= 'Strategy Example 0' if func is not None: #types.MethodType:将一个函数绑定到一个对象中 self.execute= types.MethodType(func,self) def execute(self): print(self.name) def execute_replacement1(self): print(self.name+ ' from execute 1') def execute_replacement2(self): print(self.name+ ' from execute 2') if __name__ =='__main__': strat0= StrategyExample() strat1= StrategyExample(execute_replacement1) strat1.name= 'Strategy Example 1' strat2= StrategyExample(execute_replacement2) strat2.name= 'Strategy Example 2' strat0.execute() strat1.execute() strat2.execute()