设计模式之:工厂+策略+模板

大量if else操作的优化:

if a:
   ado
elif b:
   bdo
elif c:
   cdo

思路:

使用策略模式将ado,bdo,cdo操作合并到策略类中, 即抽象成为不同的策略类,通过不同的策略类,来实现对不同对象执行定制方法的效果

class StrategyHandlerForA():
        def do
class StrategyHandlerForA():
        def do
 class StrategyHandlerForA():
         def do

使用工厂方法管理策略类

def singleton(cls):
        cls_instance = {}
        def get_instance():
               if cls not in cls_instance:
                      cls_instance[cls] = cls()
                return  cls_instance[cls] 
        return get_instance


@singleton
 class FactoryHandler():
                
        def __init__(self):
                 self.map = {}

        def register(self, name, handler):
                self.map[name] = handler # python 的内建函数,getattr(object,name) 就相当于 object.name,但是这里 name 可以为变量。

         def getInvokeStrategy():
                  return self.map[name]

若需要抽象为不同的策略类,需要对策略接口进行统一的话,需要使用模板方法

# 使用 python 元类解决这个问题

class BaseMetaClass(type):
          
        def __new__(cls, name, bases, attrs):
                    # 在元类中自动注册到factory的单例中
        def do()
      
        def other_do()
              raiseNotImplementError
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容