Python与设计模式(一)——Abstract Factory
来源:互联网 发布:淘宝网1 8米纯棉床罩 编辑:程序博客网 时间:2024/06/04 19:09
最近在重新学习Python,想找一些优秀的Python源代码阅读学习,加上前段时间一直在学习设计模式,所以选择了GitHub上这个项目作为学习对象:
https://github.com/faif/python-patterns
这里有用Python实现各个设计模式的源代码demo。
本篇从Abstract Factory开始介绍。
其源码如下:
#!/usr/bin/env python# -*- coding: utf-8 -*-# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/"""Implementation of the abstract factory pattern"""import siximport abcimport randomclass PetShop(object): """A pet shop""" def __init__(self, animal_factory=None): """pet_factory is our abstract factory. We can set it at will.""" self.pet_factory = animal_factory def show_pet(self): """Creates and shows a pet using the abstract factory""" pet = self.pet_factory.get_pet() print("We have a lovely {}".format(pet)) print("It says {}".format(pet.speak())) print("We also have {}".format(self.pet_factory.get_food()))# Stuff that our factory makesclass Dog(object): def speak(self): return "woof" def __str__(self): return "Dog"class Cat(object): def speak(self): return "meow" def __str__(self): return "Cat"# Factory classesclass DogFactory(object): def get_pet(self): return Dog() def get_food(self): return "dog food"class CatFactory(object): def get_pet(self): return Cat() def get_food(self): return "cat food"# Create the proper familydef get_factory(): """Let's be dynamic!""" return random.choice([DogFactory, CatFactory])()# Implementation 2 of an abstract factory@six.add_metaclass(abc.ABCMeta)class Pet(object): @classmethod def from_name(cls, name): for sub_cls in cls.__subclasses__(): if name == sub_cls.__name__.lower(): return sub_cls() @abc.abstractmethod def speak(self): """"""class Kitty(Pet): def speak(self): return "Miao"class Duck(Pet): def speak(self): return "Quak"# Show pets with various factoriesif __name__ == "__main__": for i in range(3): shop = PetShop(get_factory()) shop.show_pet() print("=" * 20) for name0 in ["kitty", "duck"]: pet = Pet.from_name(name0) print("{}: {}".format(name0, pet.speak()))### OUTPUT #### We have a lovely Cat# It says meow# We also have cat food# ====================# We have a lovely Dog# It says woof# We also have dog food# ====================# We have a lovely Cat# It says meow# We also have cat food# ====================# kitty: Miao# duck: Quak
代码对应的类图如下:大家可能会感到奇怪:这里并没有抽象工厂啊?我们可以看这段代码:
# Create the proper familydef get_factory(): """Let's be dynamic!""" return random.choice([DogFactory, CatFactory])()
这里,其实就实现了一个抽象工厂的功能,生成目标的factory。DogFactory用来生产Dog对象,CatFactory用来生产Cat对象。Dog类和Cat类都是Pet类的子类。
阅读全文
0 0
- Python与设计模式(一)——Abstract Factory
- 设计模式一:abstract factory
- 设计模式一(Factory Method,Abstract Factory)
- 设计模式(五)——Abstract Factory模式
- 设计模式——抽象工厂模式(Abstract Factory)
- 设计模式 —— 抽象工厂模式(Abstract Factory)
- 设计模式——抽象工厂模式(Abstract Factory)
- 白话设计模式——Abstract Factory
- C# 设计模式——Abstract Factory
- 设计模式学习笔记(一)——Abstract Factory抽象工厂
- 设计模式 一 抽象工厂Abstract Factory(工厂模式)
- 设计模式——(Abstract Factory)抽象工厂
- 设计模式——抽象工厂(Abstract Factory Pattern)
- GOF设计模式-创建型模式理解与思索(一)(Abstract Factory 和Builder)
- 设计模式实战之——创建型模式(Builder、Factory method、Abstract factory)
- 设计模式(一) 抽象工厂(Abstract Factory)
- 设计模式 每日一例 Abstract Factory
- 设计模式——Abstract Factory模式、Singleton模式
- 微擎0.7功能解析:性能优化、读写分离、负载均衡、附件分离
- c++ 11 tuple实现
- java代码参考规范
- I2C
- HashMap全解析
- Python与设计模式(一)——Abstract Factory
- bzoj 1698: [Usaco2007 Feb]Lilypad Pond 荷叶池塘(BFS)
- JDK源码学习(jdk1.8)
- Dubbo 管理页面的部署
- iOS-从任何一个view中获得当前控制器
- CSR是什么样的公司?CSR蓝牙芯片有何过人之处?
- 域名--->IP 和 IP---->MAC
- hdu 6215 Brute Force Sorting
- spring+springmvc+hibernate利用poi实现导出Excel功能