我重构了一些Python代码,有一次我想出了一种我无法真正指定名称的模式(尽管我对模式不太熟悉)。
这是我所做的抽象版本的尝试:
from abc import ABC, abstractmethod
from enum import Enum
class AbstractThing(ABC):
@abstractmethod
def do_something(self):
pass
class ConcreteThingOne(AbstractThing):
def do_something(self):
print("CONCRETETHINGONE DID SOMETHING IN A WAY CONCRETETHINGONE WOULD DO IT")
class ConcreteThingTwo(AbstractThing):
def do_something(self):
print("concretethingtwo did something in a way concretethingtwo would do it")
class ThingType(Enum):
ONE = ConcreteThingOne
TWO = ConcreteThingTwo
def func_that_does_something_with_thing(thing_type: ThingType):
thing: AbstractThing = thing_type.value()
thing.do_something()
我发现这可能是一种模式,但我不太确定。
我喜欢它的地方:
thing_type
是一个枚举,可以为该用户或其 IDE 提供有关可能值的建议(与使用字典时相反)。这就是工厂方法或者策略模式。这些模式具有很好的可扩展性,就像添加新类型很简单,只需创建一个新类并更新枚举即可。您可以在这里找到有关它们的更多信息:https://realpython.com/factory-method-python/和https://refactoring.guru/design-patterns/strategy/python/example