Differences between revisions 2 and 18 (spanning 16 versions)
Revision 2 as of 2005-07-30 02:10:11
Size: 18
Editor: flyaflya
Comment:
Revision 18 as of 2005-07-31 15:15:14
Size: 5155
Editor: flyaflya
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[TableOfContents]]
Line 2: Line 4:
== 介绍 ==

== 创建型模式 ==


=== singleton(单件) ===

==== 意图 ====
保证一个类仅有一个实例,并提供一个访问它的全局访问点。

==== 实现代码 ====
{{{
#!python
class Singleton:
    """ A python singleton """

    class __impl:
        """ Implementation of the singleton interface """

        def spam(self):
            """ Test method, return singleton id """
            return id(self)

    # storage for the instance reference
    __instance = None

    def __init__(self):
        """ Create singleton instance """
        # Check whether we already have an instance
        if Singleton.__instance is None:
            # Create and remember instance
            Singleton.__instance = Singleton.__impl()

        # Store instance reference as the only member in the handle
        self.__dict__['_Singleton__instance'] = Singleton.__instance

    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)


# Test it
s1 = Singleton()
print id(s1), s1.spam()

s2 = Singleton()
print id(s2), s2.spam()

# Sample output, the second (inner) id is constant:
# 8172684 8176268
# 8168588 8176268
}}}

==== 另一个实现代码 ====

从[http://members.chello.nl/f.niessink/ TaskCoach]的代码中摘抄,因此许可证为GPL。
-- QiangningHong



{{{
#!python
class Singleton(type):
    """Singleton Metaclass"""

    def __init__(cls, name, bases, dic):
        super(Singleton, cls).__init__(name, bases, dic)
        cls.instance = None

    def __call__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
        return cls.instance
}}}

使用方法:
{{{
#!python
class MyClass(object):
    __metaclass__ = Singleton

ob1 = MyClass()
ob2 = MyClass()
assert ob1 is ob2
}}}

== 结构型模式 ==

== 行为模式 ==
=== Chain of Responsibility(职责链) ===
==== 意图 ====
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
==== 说明 ====
用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合,唯一共同点是在他们之间传递request. 也就是说,来了一个请求,A类先处理,如果没有处理,就传递到B类处理,如果没有处理,就传递到C类处理,就这样象一个链条(chain)一样传递下去。
例如,窗口UI对消息的处理:

attachment:CORPattern.gif
==== 代码实现 ====
模拟UI对消息的处理
{{{
#!python
class Event:
    def __init__( self, name ):
        self.name = name

class Widget:
    def __init__( self, parent = None ):
        self.__parent = parent
    def Handle( self, event ):
        handler = 'Handle_' + event.name
        if hasattr( self, handler ):
            method = getattr( self, handler )
            method( event )
        elif self.__parent:
            self.__parent.Handle( event )
        elif hasattr( self, 'HandleDefault' ):
            self.HandleDefault( event )
}}}

使用:
当用一个event被Handle,将调用Handle_"event.name",如果没有此函数就调用parent来处理此event,如果还没有被处理,就试着交给HandleDefault()。
例如:
{{{
#!python
class MainWindow(Widget):
    def Handle_close( self, event ):
        print 'MainWindow: ' + event.name
    def HandleDefault( self, event ):
        print 'Default: ' + event.name
        
class Button( Widget ):
    def Handle_click( self, event ):
        print 'Button: ' + event.name
}}}

=== Proxy(代理)===
==== 意图 ====
为其他对象提供一种代理以控制对这个对象的访问。

attachment:ProxyPattern.gif
==== 代码 ====
{{{
#!python
class Proxy:
    def __init__( self, subject ):
        self.__subject = subject
    def __getattr__( self, name ):
        return getattr( self.__subject, name )
}}}
例子:
{{{
#!python

class RGB:
    def __init__( self, red, green, blue ):
        self.__red = red
        self.__green = green
        self.__blue = blue
    def Red( self ):
        return self.__red
    def Green( self ):
        return self.__green
    def Blue( self ):
        return self.__blue

}}}
使用Proxy改变Blue函数:
{{{
#!python
class NoBlueProxy( Proxy ):
    def Blue( self ):
        return 0
}}}
使用:
>>> rgb = RGB( 100, 192, 240 )

>>> rgb.Red()

100

>>> proxy = Proxy( rgb )

>>> proxy.Green()

192

>>> noblue = NoBlueProxy( rgb )

>>> noblue.Green()

192

>>> noblue.Blue()

0

}}}
使用:
>>> rgb = RGB( 100, 192, 240 )

>>> rgb.Red()

100

>>> proxy = Proxy( rgb )

>>> proxy.Green()

192

>>> noblue = NoBlueProxy( rgb )

>>> noblue.Green()

192

>>> noblue.Blue()

0

TableOfContents

设计模式

介绍

创建型模式

singleton(单件)

意图

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

实现代码

   1 class Singleton:
   2     """ A python singleton """
   3 
   4     class __impl:
   5         """ Implementation of the singleton interface """
   6 
   7         def spam(self):
   8             """ Test method, return singleton id """
   9             return id(self)
  10 
  11     # storage for the instance reference
  12     __instance = None
  13 
  14     def __init__(self):
  15         """ Create singleton instance """
  16         # Check whether we already have an instance
  17         if Singleton.__instance is None:
  18             # Create and remember instance
  19             Singleton.__instance = Singleton.__impl()
  20 
  21         # Store instance reference as the only member in the handle
  22         self.__dict__['_Singleton__instance'] = Singleton.__instance
  23 
  24     def __getattr__(self, attr):
  25         """ Delegate access to implementation """
  26         return getattr(self.__instance, attr)
  27 
  28     def __setattr__(self, attr, value):
  29         """ Delegate access to implementation """
  30         return setattr(self.__instance, attr, value)
  31 
  32 
  33 # Test it
  34 s1 = Singleton()
  35 print id(s1), s1.spam()
  36 
  37 s2 = Singleton()
  38 print id(s2), s2.spam()
  39 
  40 # Sample output, the second (inner) id is constant:
  41 # 8172684 8176268
  42 # 8168588 8176268

另一个实现代码

从[http://members.chello.nl/f.niessink/ TaskCoach]的代码中摘抄,因此许可证为GPL。 -- QiangningHong

   1 class Singleton(type):
   2     """Singleton Metaclass"""
   3 
   4     def __init__(cls, name, bases, dic):
   5         super(Singleton, cls).__init__(name, bases, dic)
   6         cls.instance = None
   7 
   8     def __call__(cls, *args, **kwargs):
   9         if cls.instance is None:
  10             cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
  11         return cls.instance

使用方法:

   1 class MyClass(object):
   2     __metaclass__ = Singleton
   3 
   4 ob1 = MyClass()
   5 ob2 = MyClass()
   6 assert ob1 is ob2

结构型模式

行为模式

Chain of Responsibility(职责链)

意图

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

说明

用一系列类(classes)试图处理一个请求request,这些类之间是一个松散的耦合,唯一共同点是在他们之间传递request. 也就是说,来了一个请求,A类先处理,如果没有处理,就传递到B类处理,如果没有处理,就传递到C类处理,就这样象一个链条(chain)一样传递下去。 例如,窗口UI对消息的处理:

attachment:CORPattern.gif

代码实现

模拟UI对消息的处理

   1 class Event:
   2     def __init__( self, name ):
   3         self.name = name
   4 
   5 class Widget:
   6     def __init__( self, parent = None ):
   7         self.__parent = parent
   8     def Handle( self, event ):
   9         handler = 'Handle_' + event.name
  10         if hasattr( self, handler ):
  11             method = getattr( self, handler )
  12             method( event )
  13         elif self.__parent:
  14             self.__parent.Handle( event )
  15         elif hasattr( self, 'HandleDefault' ):
  16             self.HandleDefault( event )   

使用: 当用一个event被Handle,将调用Handle_"event.name",如果没有此函数就调用parent来处理此event,如果还没有被处理,就试着交给HandleDefault()。 例如:

   1 class MainWindow(Widget):
   2     def Handle_close( self, event ):
   3         print 'MainWindow: ' + event.name
   4     def HandleDefault( self, event ):
   5         print 'Default: ' + event.name
   6         
   7 class Button( Widget ):
   8     def Handle_click( self, event ):
   9         print 'Button: ' + event.name

=== Proxy(代理)===

意图

为其他对象提供一种代理以控制对这个对象的访问。

attachment:ProxyPattern.gif

代码

   1 class Proxy:
   2     def __init__( self, subject ):
   3         self.__subject = subject
   4     def __getattr__( self, name ):
   5         return getattr( self.__subject, name )   

例子:

   1 class RGB:
   2     def __init__( self, red, green, blue ):
   3         self.__red = red
   4         self.__green = green
   5         self.__blue = blue
   6     def Red( self ):
   7         return self.__red
   8     def Green( self ):
   9         return self.__green
  10     def Blue( self ):
  11         return self.__blue 

使用Proxy改变Blue函数:

   1 class NoBlueProxy( Proxy ):
   2     def Blue( self ):
   3         return 0

使用: >>> rgb = RGB( 100, 192, 240 )

>>> rgb.Red()

100

>>> proxy = Proxy( rgb )

>>> proxy.Green()

192

>>> noblue = NoBlueProxy( rgb )

>>> noblue.Green()

192

>>> noblue.Blue()

0

}}} 使用: >>> rgb = RGB( 100, 192, 240 )

>>> rgb.Red()

100

>>> proxy = Proxy( rgb )

>>> proxy.Green()

192

>>> noblue = NoBlueProxy( rgb )

>>> noblue.Green()

192

>>> noblue.Blue()

0

designpattern (last edited 2009-12-25 07:10:09 by localhost)