|
| 1 | +""" |
| 2 | +Flyweight Design Pattern |
| 3 | + Desc: Sharing the shareable data between the common classes and thus reducing the memory usage |
| 4 | + Code: Believing that every person in a family will have same genetic structure, we will create a code to learn about |
| 5 | + genetics of each family. If a same member of a family is given, no new object is created. (You can also create new |
| 6 | + objects unlike here but keep a reference of the heavy weighted one in the new |||r object). |
| 7 | +""" |
| 8 | + |
| 9 | +class ComplexGenetics(object): |
| 10 | + """ returns a huge genetic pattern""" |
| 11 | + def __init__(self): |
| 12 | + pass |
| 13 | + |
| 14 | + def genes(self, gene_code): |
| 15 | + return "ComplexPatter[%s]TooHugeinSize" % (gene_code) |
| 16 | + |
| 17 | +class Families(object): |
| 18 | + """ To learn about Family Genetic Pattern """ |
| 19 | + family = {} |
| 20 | + def __new__(cls, name, family_id): |
| 21 | + """ i have to capture the details before the class is created, __init__ is pseudo constructor """ |
| 22 | + try: |
| 23 | + id = cls.family[family_id] |
| 24 | + except KeyError: |
| 25 | + id = object.__new__(cls) |
| 26 | + cls.family[family_id] = id |
| 27 | + return id |
| 28 | + |
| 29 | + def set_genetic_info(self, genetic_info): |
| 30 | + cg = ComplexGenetics() |
| 31 | + self.genetic_info = cg.genes(genetic_info) |
| 32 | + |
| 33 | + def get_genetic_info(self): |
| 34 | + return (self.genetic_info) |
| 35 | + |
| 36 | +def test(): |
| 37 | + # name, family_id and genetic code details (i dont care if genetic code detail varies in same family [it is research fault :-D ]) |
| 38 | + data = (('a', 1, 'ATAG'), ('a', 2, 'AAGT'), ('b', 1, 'ATAG')) |
| 39 | + family_objects = [] |
| 40 | + for i in data: |
| 41 | + obj = Families(i[0], i[1]) |
| 42 | + obj.set_genetic_info(i[2]) |
| 43 | + family_objects.append(obj) |
| 44 | + |
| 45 | + for i in family_objects: |
| 46 | + print "id = " + str(id(i)) |
| 47 | + print i.get_genetic_info() |
| 48 | + print "similar id's says that they are same objects " |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + test() |
0 commit comments