banner
Jul 5, 2023
118 Views

Flyweight Pattern

Written by
banner

In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects.

Trong lập trình máy tính, mẫu thiết kế phần mềm Flyweight (Cái cân) đề cập đến một đối tượng giảm thiểu việc sử dụng bộ nhớ bằng cách chia sẻ một số dữ liệu với các đối tượng tương tự khác.

Ví dụ chúng ta có các hình hình học cơ bản như hình vuông, hình tròn và hình chữ nhật. Mỗi hình có các thuộc tính như màu sắc và kích thước, và chúng ta muốn vẽ nhiều hình hình học trên màn hình. Để sử dụng Flyweight trong ví dụ này, chúng ta có thể tạo một lớp Flyweight để đại diện cho các đối tượng hình hình học, và sử dụng một Flyweight Factory để quản lý và chia sẻ các đối tượng Flyweight này.

import random


class ShapeFlyweight:
    def draw(self, color):
        pass


class CircleFlyweight(ShapeFlyweight):
    def draw(self, color):
        print(f"Drawing a circle with color {color}")


class SquareFlyweight(ShapeFlyweight):
    def draw(self, color):
        print(f"Drawing a square with color {color}")


class RectangleFlyweight(ShapeFlyweight):
    def draw(self, color):
        print(f"Drawing a rectangle with color {color}")


class ShapeFlyweightFactory:
    def __init__(self):
        self._flyweights = {}

    def get_flyweight(self, shape_type):
        if shape_type not in self._flyweights:
            if shape_type == 'circle':
                self._flyweights[shape_type] = CircleFlyweight()
            elif shape_type == 'square':
                self._flyweights[shape_type] = SquareFlyweight()
            elif shape_type == 'rectangle':
                self._flyweights[shape_type] = RectangleFlyweight()
        return self._flyweights[shape_type]


class DrawingApp:
    def __init__(self, flyweight_factory):
        self.flyweight_factory = flyweight_factory
        self.shapes = []

    def add_shape(self, shape_type, color):
        flyweight = self.flyweight_factory.get_flyweight(shape_type)
        self.shapes.append((flyweight, color))

    def draw_shapes(self):
        for shape, color in self.shapes:
            shape.draw(color)


if __name__ == '__main__':
    flyweight_factory = ShapeFlyweightFactory()
    drawing_app = DrawingApp(flyweight_factory)

    # Thêm các hình hình học vào ứng dụng vẽ
    drawing_app.add_shape('circle', 'red')
    drawing_app.add_shape('square', 'blue')
    drawing_app.add_shape('circle', 'green')

    # Vẽ các hình hình học
    drawing_app.draw_shapes()

output: Bạn thấy dù có vẽ bao nhiêu hình thì mỗi loại hình cũng chỉ khởi tạo 1 lần.

creating CircleFlyweight
creating SquareFlyweight
Drawing a circle with color red
Drawing a square with color blue
Drawing a circle with color green
Drawing a circle with color blue
Drawing a circle with color pink
Drawing a circle with color orange
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *