• 策略模式


    网站参考:

    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 them
    interchangeable. Strategy lets the algorithm vary independently from
    clients that use it.
    """
    
    import abc
    
    
    class 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):
            pass
    
    
    class ConcreteStrategyA(Strategy):
        """
        Implement the algorithm using the Strategy interface.
        """
    
        def algorithm_interface(self):
            pass
    
    
    class ConcreteStrategyB(Strategy):
        """
        Implement the algorithm using the Strategy interface.
        """
    
        def algorithm_interface(self):
            pass
    
    
    def 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   当抽象基类中出现这个装饰器意味着子类中这个方法必须实现

  • 相关阅读:
    tcp/ip的通俗讲述(转)
    linux中的read_link
    浅拷贝和深拷贝
    JAVA的动态代理Jdk实现方式
    友元函数
    孤儿进程、僵尸进程
    waitpid()函数
    wait()函数
    dup2函数
    exec族函数
  • 原文地址:https://www.cnblogs.com/bill2014/p/16287511.html
Copyright © 2020-2023  润新知