Wednesday 29 April 2009

Flyweight Pattern

If anyone was wondering what I meant when I said I wanted to do ideological change to Magento - this is one of them:

http://github.com/markkimsal/agent-ohm/commit/0c2e5d0885d1c45e1ba847950c8636aca75f9d95

I simply changed the URL to use the flyweight pattern, thus eliminating the repeated conversion of the code "core/url" to Mage_Core_Model_Url.

The name "Mage_Core_Model_Url" is just as flexible and just as inflexible as using the same token everywhere, namely "core/url". Some of you might think that just because the class's name is "hard-coded" into the source that it must only deal with an instance of itself, but that just isn't true. In the same way that Mage::getModel() dishes out various instances of different classes, any class in Magento can operate as a "master of its domain", doling out various configurable instances.

What good is it to spread out the workload of converting tokens to class names, you ask? Well, it tends to avoid recursive loops, it's not guaranteed, but it can make needless recursion easier to spot. It's also easier to benchmark parts of the code if the responsibility for creating every object isn't centralized.

But, this change isn't just about spreading out responsibility or patterns. It's a good, efficient way to avoid repetitive class name look-ups and costly object instantiation for an often used object. The use of "clone" copies an existing object, and if that object's constructor is complicated that can save on total execution of the page.

No comments: