ruk·si

🐍 Python
Flyweight

Updated at 2012-12-11 17:31

Flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.

class CoffeeOrder(object):
    def serveCoffee(self, context):
        pass
class CoffeeOrderContext(object):

    def __init__(self, table_number):
        self._table_number = table_number

    def getTable(self):
        return self._table_number
class CoffeeFlavor(CoffeeOrder):

    def __init__(self, new_flavor):
        self._flavor = new_flavor

    def getFlavor(self):
        return self._flavor

    def serveCoffee(self, context):
        str1 = str(self.getFlavor())
        str2 = str(context.getTable())
        print('Serving {0} to table {1}'.format(str1, str2))
#!/usr/bin/python
# -*- coding: UTF-8 -*-

class CoffeeFlavorFactory(object):

    # Python dictionary is internally a hash map or hash table.
    _flavors = dict()

    def getCoffeeFlavor(self, flavor_name):
        try:
            flavor = self._flavors[flavor_name]
        except KeyError:
            flavor = CoffeeFlavor(flavor_name)
            self._flavors[flavor_name] = flavor
        return flavor

    def getTotalCoffeeFlavorsMade(self):
        return len(self._flavors)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Test(object):

    def __init__(self):
        self.flavors = [] # Use static arrays if possible
        self.tables = []
        self.ordersMade = 0
        self.flavorFactory = CoffeeFlavorFactory()

    def takeOrders(self, flavorIn, table):
        self.flavors.append(self.flavorFactory.getCoffeeFlavor(flavorIn))
        self.tables.append(CoffeeOrderContext(table))
        self.ordersMade += 1

    def run(self):
        self.takeOrders("Cappuccino", 2);
        self.takeOrders("Cappuccino", 2);
        self.takeOrders("Frappe", 1);
        self.takeOrders("Frappe", 1);
        self.takeOrders("Xpresso", 1);
        self.takeOrders("Frappe", 897);
        self.takeOrders("Cappuccino", 97);
        self.takeOrders("Cappuccino", 97);
        self.takeOrders("Frappe", 3);
        self.takeOrders("Xpresso", 3);
        self.takeOrders("Cappuccino", 3);
        self.takeOrders("Xpresso", 96);
        self.takeOrders("Frappe", 552);
        self.takeOrders("Cappuccino", 121);
        self.takeOrders("Xpresso", 121);

        for i in range(0, self.ordersMade-1):
            self.flavors[i].serveCoffee(self.tables[i]);

        print()
        str3 = str(self.flavorFactory.getTotalCoffeeFlavorsMade())
        print("Total coffee flavor objects made: " + str3)

print
x = Test()
x.run()