享元模式是一种结构型设计模式,通过共享相同对象来减少内存消耗,从而提高系统性能。它适用于大量细粒度对象的场景,这些对象具有相同或相似的状态和行为 。
在这篇文章中,我们将深入探讨享元模式这一设计模式,作为一位优秀的评测编程专家,我希望通过这篇内容帮助大家更好地理解和应用享元模式,从而提高程序的性能和可维护性。
让我们来了解一下什么是享元模式,享元模式是一种结构型设计模式,它通过共享技术有效地减少了系统中的类和对象的数量,从而降低了系统的整体开销,在享元模式中,一个对象可以被多个其他对象共享,这样就可以避免创建大量的冗余对象,从而节省内存空间。
享元模式的主要优点如下:
1、减少系统开销:通过共享技术,享元模式可以有效地减少系统中的类和对象的数量,从而降低系统的整体开销。
2、提高性能:由于享元模式可以避免创建大量的冗余对象,因此可以提高系统的运行速度。
3、简化系统结构:享元模式可以帮助我们将系统中的复杂性隐藏起来,使得系统更加简洁易懂。
我们将通过一个简单的示例来演示如何使用享元模式,假设我们有一个动物园系统,其中包含了多种动物,如狮子、老虎、长颈鹿等,为了节省内存空间,我们可以使用享元模式来实现这些动物的共享。
我们定义一个动物基类 Animal:
class Animal: def __init__(self, name): self.name = name
我们为每种具体的动物创建一个子类,并继承自 Animal 基类:
class Lion(Animal): def speak(self): return "嗷呜" class Tiger(Animal): def speak(self): return "喵喵" class Giraffe(Animal): def speak(self): return "咩咩"
我们定义一个享元类 AbstractFlyweight:
from abc import ABC, abstractmethod class AbstractFlyweight(ABC): @abstractmethod def operation(self): pass
我们为每种具体的动物创建一个享元对象,并继承自 AbstractFlyweight:
class LionFlyweight(AbstractFlyweight): def __init__(self, name): self._name = name def operation(self): return f"{self._name}说:我是最勇敢的狮子!" class TigerFlyweight(AbstractFlyweight): def __init__(self, name): self._name = name def operation(self): return f"{self._name}说:我是最强壮的老虎!"
我们定义一个工厂类 FlyweightFactory,用于创建和管理享元对象:
class FlyweightFactory: _flyweights = {} _shared_name = "共享动物" _shared_age = 1000000000000000000L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 1000000000000000L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 10000000000000L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 10000000000L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 10000L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 1L // len(Animal) // len(Lion) // len(Tiger) // len(Giraffe) + 1; _counter = itertools.count() if hasattr(__builtins__, 'itertools') else count() # Python >=2.5 has itertools module; otherwise use built-in count function for creating unique counter object. _index = dict((key(), index) for index, key in enumerate(Animal)) # mapping of keys to indexes for efficient lookup by key in the flyweight instances. _flyweights[_shared_name] = LionFlyweight("大") # create shared instance of lion. _flyweights[f"{_shared_name}{next(_counter)}"] = LionFlyweight("小") # create shared instance of lion with unique name and age (to simulate dynamic behavior). _flyweights[f"{_shared_name}{next(_counter)}"] = TigerFlyweight("大") # create shared instance of tiger with unique name and age (to simulate dynamic behavior). _flyweights[f"{_shared_name}{next(_counter)}"] = TigerFlyweight("小") # create shared instance of tiger with unique name and age (to simulate dynamic behavior). _flyweights[f"{_shared_name}{next(_counter)}"] = GiraffeFlyweight("大") # create shared instance of giraffe with unique name and age (to simulate dynamic behavior). _flyweights[f"{_shared_name}{next(_counter)}"] = GiraffeFlyweight("小") # create shared instance of giraffe with unique name and age (to simulate dynamic behavior). def get_flyweight(self, key): # retrieves the flyweight object associated with the given key. try: value = self._flyweights[key] except KeyError: raise ValueError("No flyweight object exists for the given key: %s" % key) return value def increment_age(self, key): # increases the age of the flyweight object associated with the given key. try: value = self._flyweights[key] except KeyError: raise ValueError("No flyweight object exists for the given key: %s" % key) value.age += next(self._counter) return value def decrement_age(self, key): # decreases the age of the flyweight object associated with the given key. try: value = self._flyweights[key] except KeyError: raise ValueError("No flyweight object exists for the given key: %s" % key) value.age += next(self._counter) return value def add_child(self, parent_key, child_key): # adds a child to the flyweight object associated with the given parent key. try: parent = self._flyweights[parent_key] except KeyError: raise ValueError("No flyweight object exists for the given parent key: %s" % parent_key) try: child = self._flyweights[child_key] except KeyError: raise ValueError("No flyweight object exists for the given child key: %s" % child_key) parent.children.append(child) return True def remove_child(self, parent_key, child_key): # removes a child from the flyweight object associated with the given parent key. try: parent = self._flyweights[parent_key] except KeyError: raise ValueError("No flyweight object exists for the given parent key: %s" % parent_key) try: child = self._flyweights[child_key] except KeyError: raise ValueError("No flyweight object exists for the given child key: %s" % child_key) parent.children.remove(child) return True def get_children(self, parent_key): # retrieves all children of the flyweight object associated with the given parent key. try: parent = self._flyweights[parent_key] except KeyError: raise ValueError("No flyweight object exists for the given parent key: %s" % parent_key) return [child for child in parent.children] def get_allkeys(): # retrieves all keys in the factory's flyweight map dictionary. return list([key for key in self._index]) def reset(): # resets factory's state so that new instances can be created using it again after cleanup is complete. self.reset() def resettable(): # returns True if factory's state can be reset; False otherwise. return True def cleanup(): # clean up unused flyweights by removing them from factory's internal map dictionary and releasing their resources if necessary; also reset factory's state to prepare it for reuse after cleanup is complete. return [value for value in list(self._index.values()) if not value.isactive()], self.reset()```