一分鐘了解flyweight pattern
Flyweight Pattern 是一種常用的設(shè)計模式,它可以減少程序運行時的內(nèi)存消耗,提高程序的性能。在 Python 中,F(xiàn)lyweight Pattern 可以用于共享對象的創(chuàng)建和管理,以減少程序的內(nèi)存消耗。
?下面我們將用一個簡單的例子來說明這個模式。
?假設(shè)我們正在開發(fā)一個棋盤游戲程序,這個程序需要創(chuàng)建和管理大量的棋子對象。每個棋子對象都有自己的屬性,比如顏色、形狀等,而且這些屬性可以隨時修改。這個程序需要在運行時動態(tài)創(chuàng)建棋子對象,并且需要盡可能地節(jié)省內(nèi)存。我們需要設(shè)計一個程序,用于創(chuàng)建和管理這些棋子對象,并提供一組簡單的接口,供用戶來控制棋盤游戲的功能。
?我們首先定義一個棋子類 ChessPiece,它用于表示一個棋子對象。這個類包含棋子的顏色和形狀等屬性,并提供相應(yīng)的控制接口。
class ChessPiece:
? ? def __init__(self, color, shape):
? ? ? ? self.color = color
? ? ? ? self.shape = shape
? ? ?def set_color(self, color):
? ? ? ? self.color = color
? ? ?def set_shape(self, shape):
? ? ? ? self.shape = shape
? ? ?def get_color(self):
? ? ? ? return self.color
? ? ?def get_shape(self):
? ? ? ? return self.shape
接下來我們定義一個棋子工廠類 ChessPieceFactory,它用于創(chuàng)建和管理棋子對象。這個類包含一個棋子對象池,用于存儲所有已經(jīng)創(chuàng)建的棋子對象。每次需要創(chuàng)建一個新的棋子對象時,這個類首先檢查棋子對象池中是否已經(jīng)存在相同顏色和形狀的對象。如果已經(jīng)存在,則直接返回已經(jīng)存在的對象;否則,創(chuàng)建一個新的棋子對象,并將其添加到棋子對象池中。
class ChessPieceFactory:
? ? def __init__(self):
? ? ? ? self.piece_pool = {}
? ? ?def get_piece(self, color, shape):
? ? ? ? key = f'{color}_{shape}'
? ? ? ? if key not in self.piece_pool:
? ? ? ? ? ? self.piece_pool[key] = ChessPiece(color, shape)
? ? ? ? return self.piece_pool[key]
最后,我們來測試這個程序。我們創(chuàng)建一個棋子工廠對象,并使用它來創(chuàng)建和管理棋子對象。
factory = ChessPieceFactory()
piece1 = factory.get_piece('red', 'circle')
piece2 = factory.get_piece('red', 'circle')
piece3 = factory.get_piece('green', 'square')
piece4 = factory.get_piece('green', 'circle')
piece5 = factory.get_piece('red', 'circle')
piece6 = factory.get_piece('red', 'square')
print(piece1 == piece2) # True
print(piece1 == piece5) # True
print(piece1 == piece6) # False
這個程序?qū)⑤敵鋈缦聝?nèi)容:
True
True
False
這個例子中,我們使用 Flyweight Pattern 來共享棋子對象的創(chuàng)建和管理。每次需要創(chuàng)建一個新的棋子對象時,我們首先檢查棋子對象池中是否已經(jīng)存在相同顏色和形狀的對象。如果已經(jīng)存在,則直接返回已經(jīng)存在的對象;否則,創(chuàng)建一個新的棋子對象,并將其添加到棋子對象池中。這個模式使得程序更加高效和節(jié)省內(nèi)存,而且也可以方便地擴展到支持更多的棋子屬性或者添加更多的控制接口。