The maze book for programmers!
mazesforprogrammers.com

Algorithms, circle mazes, hex grids, masking, weaving, braiding, 3D and 4D grids, spheres, and more!

DRM-Free Ebook

The Buckblog

assorted ramblings by Jamis Buck

Even better

14 November 2004 — 2-minute read

Perhaps you’ve already read my last article, Now that’s cool, in which I described a way of doing parameterized services with Needle. If you have, go ahead and forget everything it mentioned. The next version of Needle (v1.2, to be released this Thursday) has a better way.

As a result of discussions with Christian Neukirchen and Joel VanderWerf, I finally sat down and attempted to find a way to support parameterized services. If you missed my last article, parameterized services are just services that require contextual information to be given to them in order to instantiate them. Thus, you can’t really have parameterized singleton services (since singleton’s are only instantiated once), but for prototype services, it would be a real boon.

Joel also suggested multitons, which are like singletons except that they are parameterized, and they return a unique object instance for each unique parameter set. A kind of cross between prototypes and singletons.

It turned out to be almost embarassingly easy to implement both of these features. The next version of Needle will support a :multiton service model, and parameterized services. Observe:

  registry.define.printers( :model => :multiton ) { |c,p,name| Printer.new( name ) }
  mono = registry.printers( :monochrome )
  color = registry.printers( :color )
  ...

(Note that the c and p parameters are required—the first is the container that the service belongs to, and the second is the service point instance that represents the service. You use the c parameter to access other services, and the p parameter to get metadata about the current service, like fullname. The remaining parameters are contextual, given when requesting the service.)

Much nicer than the trick I demonstrated using lambda services. Although I still think lambda services are pretty slick…I imagine they may even still be useful, though I haven’t had a chance to think too much about that.