策略模式

策略模式

网站参考

https://sourcemaking.com/design_patterns/strategy

https://refactoringguru.cn/design-patterns/strategy/python/example#lang-features

代码参考:

"""Define a family of algorithms, encapsulate each one, and make theminterchangeable. Strategy lets the algorithm vary independently fromclients that use it."""import abcclass Context:    """    Define the interface of interest to clients.    Maintain a reference to a Strategy object.    """    def __init__(self, strategy):        self._strategy = strategy    def context_interface(self):        self._strategy.algorithm_interface()class Strategy(metaclass=abc.ABCMeta):    """    Declare an interface common to all supported algorithms. Context    uses this interface to call the algorithm defined by a    ConcreteStrategy.    """    @abc.abstractmethod    def algorithm_interface(self):        passclass ConcreteStrategyA(Strategy):    """    Implement the algorithm using the Strategy interface.    """    def algorithm_interface(self):        passclass ConcreteStrategyB(Strategy):    """    Implement the algorithm using the Strategy interface.    """    def algorithm_interface(self):        passdef main():    concrete_strategy_a = ConcreteStrategyA()    context = Context(concrete_strategy_a)    context.context_interface()if __name__ == "__main__":    main()

上述除了学习了设计模式,还学习到了抽象基类:

1)class Strategy(metaclass=abc.ABCMeta) 抽象基类只能被继承,不能被实例化

2)@abc.abstractmethod 当抽象基类中出现这个装饰器意味着子类中这个方法必须实现

免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部