a single class supporting multiple facets/interfaces

Jp Calderone exarkun at intarweb.us
Mon Jan 20 17:47:14 EST 2003


On Mon, Jan 20, 2003 at 05:46:36AM -0700, David Garamond wrote:
> i want to have a class that can support multiple sets of methods, based 
> on what the client requests. for example, see the following code:
> 
> [snip code]
> 
> if a client wants interface 1, then she will get foo and bar (which is 
> actually bar1). if he picks interface 2, then she will get foo and bar 
> (which is actually bar2). for all she cares, she just wants to know/deal 
> with a single [versatile] class, C. and from that single class, she can 
> pick several sets of features/interfaces she needs/wants.
> 
> the above code does what i want to accomplish, but i think it's very 
> ugly. can anyone make it more elegant?
> 

  Twisted provides a generalized way to get this behavior with what are
called "Interfaces", "Adapters", and "Components".  Adapters provide the
implementation for Interfaces (these two together are sort of what you term
"Facets"), while Components are the actual underlying objects that are being
operated upon.

from twisted.python import components

class C(components.Componentized):
    # C class definition omitted for brevity/clarity
    pass

class IGoodStuff(components.Interface):
    def foo(self):
        """Display some fooey goodness"""

    def bar(self):
        """Display some quality bar"""


class CAdapter(components.Adapter):
    def foo(self):
        self.original.foo()

class VersionOneAdapter(CAdapter):
    __implements__ = (IGoodStuff,)

    def bar(self):
        self.original.bar1()

class VersionTwoAdapter(CAdapter):
    __implements__ = (IGoodStuff,)

    def bar(self):
        self.original.bar2()

# Set the adapter to be used for this interface globally
components.registerAdapter(VersionOneAdapter, C, IGoodStuff)
c1 = C()
c1.getComponent(IGoodStuff).bar()

# Override the global setting for this instance only
c1.setComponent(IGoodStuff, VersionTwoAdapter(c1))
c1.getComponent(IGoodStuff).bar()


  Twisted lives at http://www.twistedmatrix.com/ and the epydocs for
Componentized are at

http://twistedmatrix.com/documents/TwistedDocs/current/api/public/twisted.python.components.Componentized.html

  Unfortunately there is no howto for components yet :(  There are some good
examples of Component usage in TR, though, which you can get via anon-cvs:

  cvs -d:pserver:anon at twistedmatrix.com:/cvs co Reality

  Jp

-- 
Elitism: It's lonely at the top, but it's comforting to look down upon
everyone at the bottom.
--
 12:00am up 35 days, 9:48, 3 users, load average: 0.61, 0.33, 0.22
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030120/b4f75b72/attachment.sig>


More information about the Python-list mailing list