python 模式集锦
2016-03-16 11:42
453 查看
摘要: 现在,仍是很怀念java啊~
那就看看python里都有哪些好的模式吧!
发布订阅模式:
发布订阅模式,是一种编程方式,消息的发送者不会将消息发送给特定的接收者,而是将不同类型的消息直接发送,并不关注订阅者是谁,订阅者只负责订阅消息,且只接收订阅过的消息不关注消息发布者
发布订阅模式——功效:解耦
代理模式:
功效:为其他对象提供一个代理以控制对这个对象的访问
状态模式:
让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能获取的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。
混入
http://my.oschina.net/u/2504425/blog/739396
那就看看python里都有哪些好的模式吧!
发布订阅模式:
发布订阅模式,是一种编程方式,消息的发送者不会将消息发送给特定的接收者,而是将不同类型的消息直接发送,并不关注订阅者是谁,订阅者只负责订阅消息,且只接收订阅过的消息不关注消息发布者
发布订阅模式——功效:解耦
#!/usr/bin/env python # -*- coding: utf-8 -*- # time @2016/3/16 11:30 create by JasonYang from collections import defaultdict container = defaultdict(list) def sub(topic, callback): if callback in container[topic]: return container[topic].append(callback) def pub(topic, *args, **kwargs): for func in container[topic]: func(*args, **kwargs) def greeting(name): print "hello %s" % name sub('greet', greeting) pub('greet', 'dashu')
代理模式:
功效:为其他对象提供一个代理以控制对这个对象的访问
# -*- coding:utf-8 -*- # 2016/8/18 # mail:ybs.kakashi@gmail.com class Implementation(object): def f(self): print str(self.__class__) + "f()" def g(self): print str(self.__class__) + "g()" def h(self): print str(self.__class__) + "h()" class ImpProxy(object): def __init__(self): self.__impl = Implementation() def __getattr__(self, item): return getattr(self.__impl, item) p = ImpProxy() p.f() p.g() p.h()
状态模式:
让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能获取的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。
# -*- coding:utf-8 -*- # 2016/8/18 # mail:ybs.kakashi@gmail.com class State(object): def __init__(self, impl): self.__implementation = impl def change_impl(self, new_impl): self.__implementation = new_impl def __getattr__(self, item): return getattr(self.__implementation, item) class Impl1(object): def f(self): print str(self.__class__) + "f()" def g(self): print str(self.__class__) + "g()" def h(self): print str(self.__class__) + "h()" class Impl2(object): def f(self): print str(self.__class__) + "f()" def g(self): print str(self.__class__) + "g()" def h(self): print str(self.__class__) + "h()" def run(s): s.f() s.g() s.h() s.g() state = State(Impl1()) run(state) print "implementation changed" state.change_impl(Impl2()) run(state)
混入
http://my.oschina.net/u/2504425/blog/739396
相关文章推荐
- Python -- post方式上传文件
- python中属性和方法的动态绑定
- Python中with...as的用法
- 10对web开发非常又用的python包
- python 中文处理大坑
- Python中的正则表达式(re)
- python abc
- 一位大牛整理的python资源(转)
- python 基本Kmeans算法实现
- python select.epoll
- python进阶学习笔记(一):打开文件
- batch downloading file in python
- 插入排序
- julia与python中的列表解析.jl
- python学习笔记(7)-高级特性(三)-列表生成式与生成器
- python学习笔记(6)-高级特性(二)-迭代
- think python学习心得-(1)关于函数和模块
- windows系统中python2,python3共存的设置方法
- Python,pymysql简单使用。
- python中去掉HTML空格和全角Unicode空格