python 模式集锦

  • 发布订阅模式:

        发布订阅模式,是一种编程方式,消息的发送者不会将消息发送给特定的接收者,而是将不一样类型的消息直接发送,并不关注订阅者是谁,订阅者只负责订阅消息,且只接收订阅过的消息不关注消息发布者
发布订阅模式——功效:解耦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()
  • 状态模式

       让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式须要对每个系统可能获取的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。app

# -*- 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.net

相关文章
相关标签/搜索