Package pypat :: Package structural :: Module flyweight
[hide private]
[frames] | no frames]

Source Code for Module pypat.structural.flyweight

1 -class FlyweightMeta(type):
2 """ 3 Flyweight meta class as part of the Flyweight design pattern. 4 5 - External Usage Documentation: U{https://github.com/tylerlaberge/PyPatterns/wiki/Structural-Pattern-Usage} 6 - External Flyweight Pattern documentation: U{https://en.wikipedia.org/wiki/Flyweight_pattern} 7 """
8 - def __new__(mcs, name, bases, attrs):
9 """ 10 Override class construction to add 'pool' attribute to classes dict. 11 12 @param name: The name of the class. 13 @param bases: Base classes of the class. 14 @param attrs: Attributes of the class. 15 @return: A new Class. 16 """ 17 attrs['pool'] = dict() 18 return super(FlyweightMeta, mcs).__new__(mcs, name, bases, attrs)
19 20 @staticmethod
21 - def _serialize(cls, *args, **kwargs):
22 """ 23 Serialize arguments to a string representation. 24 """ 25 serialized_args = [str(arg) for arg in args] 26 serialized_kwargs = [str(kwargs), cls.__name__] 27 28 serialized_args.extend(serialized_kwargs) 29 30 return ''.join(serialized_args)
31
32 - def __call__(cls, *args, **kwargs):
33 """ 34 Override call to use objects from a pool if identical parameters are used for object creation. 35 36 @param args: Arguments for class instantiation. 37 @param kwargs: Keyword arguments for class instantiation. 38 @return: A new instance of the class. 39 """ 40 key = FlyweightMeta._serialize(cls, *args, **kwargs) 41 pool = getattr(cls, 'pool', {}) 42 43 instance = pool.get(key) 44 if not instance: 45 instance = super(FlyweightMeta, cls).__call__(*args, **kwargs) 46 pool[key] = instance 47 48 return instance
49