Null Object Design Pattern (Python recipe)

Null Object 我的感受很是有用。也是在review公司其餘同事寫代碼的時候看到。python

當時使用了flask的request全局請求變量g,而後使用了g.x保存了一個東西。json

當時在view代碼讀取g.x的時候震驚了,由於這一段代碼並無保存g.x,按道理來講應該是一個空值,當我拿着空值去調用其屬性的時候應該會報AttributeError。flask

可是什麼也沒有發生,既沒有報錯,也沒有發生什麼,並且對其判斷仍是False,因而查看其實現才發現了這個。如下所有轉自http://code.activestate.com/recipes/68205/ide

 

#!/user/bin/env python
# coding: utf-8
# {{{ http://code.activestate.com/recipes/68205/ (r1)

"""null.py

This is a sample implementation of the 'Null Object' design pattern.

Roughly, the goal with Null objects is to provide an 'intelligent'
replacement for the often used primitive data type None in Python or
Null (or Null pointers) in other languages. These are used for many
purposes including the important case where one member of some group
of otherwise similar elements is special for whatever reason. Most
often this results in conditional statements to distinguish between
ordinary elements and the primitive Null value.

Among the advantages of using Null objects are the following:

  - Superfluous conditional statements can be avoided
    by providing a first class object alternative for
    the primitive value None.

  - Code readability is improved.

  - Null objects can act as a placeholder for objects
    with behaviour that is not yet implemented.

  - Null objects can be replaced for any other class.

  - Null objects are very predictable at what they do.

To cope with the disadvantage of creating large numbers of passive
objects that do nothing but occupy memory space Null objects are
often combined with the Singleton pattern.

For more information use any internet search engine and look for
combinations of these words: Null, object, design and pattern.

Dinu C. Gherman,
August 2001
"""


class Null(object):

    """A class for implementing Null objects.

    This class ignores all parameters passed when constructing or
    calling instances and traps all attribute and method requests.
    Instances of it always (and reliably) do 'nothing'.

    The code might benefit from implementing some further special
    Python methods depending on the context in which its instances
    are used. Especially when comparing and coercing Null objects
    the respective methods' implementation will depend very much
    on the environment and, hence, these special methods are not
    provided here.
    """

    # object constructing

    def __init__(self, *args, **kwargs):
        "Ignore parameters."
        return None

    # object calling

    def __call__(self, *args, **kwargs):
        "Ignore method calls."
        return self

    def next(self):
        raise StopIteration

    def __len__(self):
        return 0

    def __eq__(self, other):
        return self is other

    # misc.

    def __repr__(self):
        "Return a string representation."
        return "<Null>"

    def __str__(self):
        "Convert to a string and return it."
        return ""

    def default(self):
        return ""

    def __nonzero__(self):
        return False

    def for_json(self):
        return ''

    __sub__ = __div__ = __mul__ = __floordiv__ = __mod__ = __and__ = __or__ = \
        __xor__ = __rsub__ = __rdiv__ = __rmul__ = __rfloordiv__ = __rmod__ = \
        __rand__ = __rxor__ = __ror__ = __radd__ = __pow__ = __rpow__ = \
        __rshift__ = __lshift__ = __rrshift__ = __rlshift__ = __truediv__ = \
        __rtruediv__ = __add__ = __getitem__ = __neg__ = __pos__ = __abs__ = \
        __invert__ = __setattr__ = __getattr__ = __delattr__ = __delitem__ = __setitem__ = \
        __iter__ = __call__


Null = Null()

這裏咱們在其餘地方引用的時候能夠直接從這個文件裏引入Null,在須要的時候返回這個Null對象實例就能夠了。ui

 

Reference:this

http://code.activestate.com/recipes/68205/ ---Null Object Design Pattern (Python recipe)spa

相關文章
相關標籤/搜索