根据《四人帮》一书,Flyweight设计模式的结构指出,应从Flyweight继承混凝土Flyweight(内部状态)和非共享混凝土Flyweight(外部状态)。在Wikipedia上可以看到类似的结构。
但是,在下面的示例中,我没有从Flightweight Shape 继承混凝土Flyweight Color 。但是,相反,我将其用作非共享混凝土跳线 Circle 的组成。
所以,我想知道我是否有一个有效的Flyweight Deisgn模式示例。在测试部分,您会注意到将仅创建两个对象 Color (黑色和红色),并且它们将在 Circle 对象之间共享,这是主要目的设计模式的设计,对吧?
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)
测试:
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("\n\nMy circles:\n")
for circle in my_circles:
circle.draw()
print()