Flyweight Design Pattern Example


Flyweight Design Pattern Example



The structure of the Flyweight design pattern, according to the Gang of Four book, states that both Concrete Flyweight (instrinsic state) and Unshared Concrete Flyweight (extrinsic state) should be inherited from Flyweight. A similar structure can be seen on Wikipedia.



However, in my following example, I didn't inherited the Concrete Flyweight Color from the Flyweight Shape. But instead, I used it as a composition of the Unshared Concrete Flyweight Circle.



So, I wonder if I have a valid example of a Flyweight Deisgn Pattern. In the testing section you can notice that only two objects Color will be created (black and red), and they will be shared among the Circle objects, which is the main intention of the Flyweight design pattern, right?


from abc import ABC, abstractmethod


# Flyweight Factory
class Shape_Factory:

color_map = {}

@staticmethod
def get_color(color):

try:
color_obj = Shape_Factory.color_map[color]
except KeyError:
color_obj = Color(color)
Shape_Factory.color_map[color] = color_obj
print("Creating color: " + color)

return color_obj


# Flyweight
class Shape(ABC):

def __init__(self, color):
self.color_obj = Shape_Factory.get_color(color)

@abstractmethod
def draw(self):
pass


# Shared Flyweight
class Color:

color = ''

def __init__(self, color):
self.color = color

def __str__(self):
return self.color


# Unshared Concrete Flyweight
class Circle(Shape):

def __init__(self, color, x, y, radius):
super().__init__(color)
self.x = x
self.y = y
self.radius = radius

def draw(self):
print("Circle: ncolor:", self.color_obj, "nx:", self.x, "ny:", self.y, "nradius:", self.radius)



Testing:


my_circles =

circle = Circle("black", x=10, y=20, radius=30)
circle.draw()
my_circles.append(circle)
print()

circle = Circle("black", x=40, y=50, radius=60)
circle.draw()
my_circles.append(circle)
print()

circle = Circle("red", x=70, y=80, radius=90)
circle.draw()
my_circles.append(circle)

print("nnMy circles:n")
for circle in my_circles:
circle.draw()
print()









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.