这种模式叫什么?这是一个好的实践吗?策略模式?

问题描述 投票:0回答:1

我重构了一些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 提供有关可能值的建议(与使用字典时相反)。
  • 将枚举名称映射到类可以让您跳过编写工厂时会得到的大量“样板代码”(如果是其他梯子,则可能又大又难看)。
python design-patterns
1个回答
0
投票

这就是工厂方法或者策略模式。这些模式具有很好的可扩展性,就像添加新类型很简单,只需创建一个新类并更新枚举即可。您可以在这里找到有关它们的更多信息:https://realpython.com/factory-method-python/https://refactoring.guru/design-patterns/strategy/python/example

© www.soinside.com 2019 - 2024. All rights reserved.