如何使用设计模式
创建型模式
工厂模式
# -*- coding:utf-8 -*-
class Factory:
def createAnimal(self, Animal):
if Animal == "Duck":
return Duck()
elif Animal == "Chick":
return Chick()
class Animal:
def __str__(self):
return "animal"
class Duck(Animal):
def __str__(self):
return "duck"
class Chick(Animal):
def __str__(self):
return "chick"
if __name__ == "__main__":
factory = Factory()
print factory.createAnimal("Duck")
print factory.createAnimal("Chick")
duck
chick
结构型模式
行为型模式
什么是设计模式
设计模式是面向对象程序设计的解决方案,是复用性程序设计的经验总结。
设计模式的目标是形成典型问题的解决方案,设计出可复用的软件结构。
设计模式根据使用目的不同而分为创建型模式,结构型模式和行为型模式
创建型模式提出了对象创建的解决方案以及数据封装的方法;包括工厂模式,抽象工厂模式,单例模式以及生成器模式。
结构型模式提出了对象之间的体系结构;包括适配器模式、桥模式、组合模式、装饰器模式以及外观模式。
行为型模式提出了对象之间的交互和各自的职责;包括迭代器模式、解释器模式、中介者模式以及观察者模式。