Singleton?

Alex Martelli aleax at aleax.it
Tue Jan 29 11:53:36 EST 2002


"James T. Dennis" <jadestar at idiom.com> wrote in message
news:a357io$pd9$1 at news.idiom.com...
    ...
>  Now, unto other patterns.  Anyone show me an example of a flyweight?

Borg is quite close to Flyweight (FW for short).  Key difference one:
in Borg you have one shared state, in FW you have a small number of
shared-states (a 'pool' of objects); a FW typically has methods that
accept 'extrinsic-state' as arguments (and use in addition to the FW's
own state).

Suppose for example that you have a number of specialized spelling
checker objects.  A specialized spelling checker object has a basic
word list (which it can share with all the spelling checkers for the
same language) and adds a few specific extra words (e.g., surnames).

Let's say there's behavior (or something best presented as such) as
well as underlying data, e.g. per-language specialized ways to best
suggest word-replacements that may take into account frequent typos
in that specific natural language.

Now, a flyweight approach to this might be (simplifying a lot...):

class BasicChecker:
    def suggestReplacements(aWord, extraWords):
        if aword in extraWords: return aWord
        return self._suggestReplacements(aWord)
    # snipped lots and lots

class BasicCheckerFactory:
    def __init__(self):
        basicCheckers = {}
    def getBasicChecker(languageName):
        try: return basicCheckers[languageName]
        except KeyError: pass
        basicChecker = self._loadFromFile(languageName)
        basicCheckers[languageName] = basicChecker
        return basicChecker
    # snipped lots and lots
basicCheckerFactory = BasicCheckerFactory()

class SpecializedChecker:
    def __init__(languageName, extraWords={}):
        self.basicChecker = basicCheckerFactory(languageName)
        self.extraWords = extraWords
    def suggestReplacements(aWord):
        return self.basicChecker.suggestReplacements(
            aWord, self.extraWords)
    # snipped lots and lots

I wonder if I snipped too much or if I managed to get the key
ideas across... basically, several SpecializedChecker instances,
each a very lightweight object, can share the same BasicChecker
instance, which can be rather heavy since its costs are anyway
"amortized" over the specialized checkers that share it.


Alex






More information about the Python-list mailing list