• Python: Chain of Responsibility


    DuChain.py

    # 责任链模式 Chain of Responsibility
    
    import enum
    
    
    # Item Types:
    # An enum we'll attach to every game object to specify type:
    # Requires Python 3.4 +
    class ItemType(enum.Enum):
       Sword = 0,
       Armor = 1,
       Potion = 2,
       Ring = 3,
       QuestItem = 4,
    
       Undefined = 5
    
    # Equipment Item:
    # For brevity, we'll just use a base class.
    # In a real-world scenario, you'd want to subclass for more abilities.
    class EquipmentItem(object):
       def __init__(self, name, itemType):
           self.name = name
           self.type = itemType
           print(str(self.name)+""+str(self.type))
    # Item Chest:
    # A sortage container class:
    class ItemChest(object):
       def __init__(self, name):
          self.chestName = name
          self.items = []
    
       def putAway(self, item):
          self.items.append(item)
    
       def printItems(self):
          # print(str(self.items.count))
          if self.items.count > 0:
             print("项目: " + str(self.chestName) + ": ")
             for item in self.items:
                print("\t" + str(item.name))
          else:
             print(str(self.chestName) + " 是空的项目!")
    # Chest Sorter Chain of Responsibility:
    class ChestSorter(object):
       def __init__(self, chest, sortType):
          self.chest = chest
          self.sortType = sortType
          self.next = None
    
       def setNext(self, sorter):
          self.next = sorter
    
       def handle(self, item):
          if item.type == self.sortType:
             self.chest.putAway(item)
          elif self.next is not None:
             self.next.handle(item)
    
       def printChain(self):
          self.chest.printItems()
          if self.next is not None:
             self.next.printChain()
    # Null Sorter:
    # The Null sorter gracefully handles a scenario where no item has a fit:
    class NullSorter(ChestSorter):
       def __init__(self, chest):
          super(NullSorter, self).__init__(chest, ItemType.Undefined)
    
       def handle(self, item):
          self.chest.putAway(item)
    
    # 二种
    class AbstractHandler(object):
       """Parent class of all concrete handlers"""
    
       def __init__(self, nxt):
          """change or increase the local variable using nxt"""
    
          self._nxt = nxt
    
       def handle(self, request):
          """It calls the processRequest through given request"""
    
          handled = self.processRequest(request)
    
          """case when it is not handled"""
    
          if not handled:
             self._nxt.handle(request)
    
       def processRequest(self, request):
          """throws a NotImplementedError"""
    
          raise NotImplementedError('第一次实现它 !')
    
    
    class FirstConcreteHandler(AbstractHandler):
       """Concrete Handler # 1: Child class of AbstractHandler"""
    
       def processRequest(self, request):
          '''return True if request is handled '''
    
          if 'a' < request <= 'e':
             print("这是 {} 处理请求的 '{}'".format(self.__class__.__name__, request))
             return True
    
    
    class SecondConcreteHandler(AbstractHandler):
       """Concrete Handler # 2: Child class of AbstractHandler"""
    
       def processRequest(self, request):
          '''return True if the request is handled'''
    
          if 'e' < request <= 'l':
             print("这是 {} 处理请求的 '{}'".format(self.__class__.__name__, request))
             return True
    
    
    class ThirdConcreteHandler(AbstractHandler):
       """Concrete Handler # 3: Child class of AbstractHandler"""
    
       def processRequest(self, request):
          '''return True if the request is handled'''
    
          if 'l' < request <= 'z':
             print("这是 {} 处理请求的 '{}'".format(self.__class__.__name__, request))
             return True
    
    
    class DefaultHandler(AbstractHandler):
       """Default Handler: child class from AbstractHandler"""
    
       def processRequest(self, request):
          """Gives the message that the request is not handled and returns true"""
    
          print("T这是 {} 告诉您请求 '{}' 现在没有处理程序.".format(self.__class__.__name__,
                                                                                            request))
          return True
    
    
    class User:
       """User Class"""
    
       def __init__(self):
          """Provides the sequence of handles for the users"""
    
          initial = None
    
          self.handler = FirstConcreteHandler(SecondConcreteHandler(ThirdConcreteHandler(DefaultHandler(initial))))
    
       def agent(self, user_request):
          """Iterates over each request and sends them to specific handles"""
    
          for request in user_request:
             self.handler.handle(request)
    

      

    main.py 调用:、

    # 责任链模式 Chain of Responsibility
    
    user = DuChain.User()
    
    string = "geovindu"
    requests = list(string)
    
    user.agent(requests)
    print("\n")
    
    swordChest = DuChain.ItemChest("剑膛")
    armorChest = DuChain.ItemChest("胸甲")
    potionChest = DuChain.ItemChest("魔药")
    otherItems = DuChain.ItemChest("杂项.")
    
    # Create the chain of responsibility:
    swords = DuChain.ChestSorter(swordChest, DuChain.ItemType.Sword)
    armor = DuChain.ChestSorter(armorChest, DuChain.ItemType.Armor)
    potions = DuChain.ChestSorter(potionChest, DuChain.ItemType.Potion)
    # Null sorter for item's that don't have an explicit chest:
    other = DuChain.NullSorter(otherItems)
    
    # Link the chains:
    swords.setNext(armor)
    armor.setNext(potions)
    potions.setNext(other)
    
    # Pointer to the head of the list:
    # Implementation note: You can create another class to maintain all the sorting items!
    sortingMachine = swords
    
    # Insert a few items into the sorting machine:
    sortingMachine.handle(DuChain.EquipmentItem("强大的剑", DuChain.ItemType.Sword))
    sortingMachine.handle(DuChain.EquipmentItem("救命药水", DuChain.ItemType.Potion))
    sortingMachine.handle(DuChain.EquipmentItem("无穷之刃", DuChain.ItemType.Sword))
    sortingMachine.handle(DuChain.EquipmentItem("护胸垫", DuChain.ItemType.Armor))
    sortingMachine.handle(DuChain.EquipmentItem("千经真理卷", DuChain.ItemType.QuestItem))
    sortingMachine.handle(DuChain.EquipmentItem("西铎的克星", DuChain.ItemType.Ring))
    
    # Display all the chests' contents: 未有对象数据
    
    # sortingMachine.printChain(sortingMachine)
    

      

    输出:

    这是 SecondConcreteHandler 处理请求的 'g'
    这是 FirstConcreteHandler 处理请求的 'e'
    这是 ThirdConcreteHandler 处理请求的 'o'
    这是 ThirdConcreteHandler 处理请求的 'v'
    这是 SecondConcreteHandler 处理请求的 'i'
    这是 ThirdConcreteHandler 处理请求的 'n'
    这是 FirstConcreteHandler 处理请求的 'd'
    这是 ThirdConcreteHandler 处理请求的 'u'
    
    
    强大的剑ItemType.Sword
    救命药水ItemType.Potion
    无穷之刃ItemType.Sword
    护胸垫ItemType.Armor
    千经真理卷ItemType.QuestItem
    西铎的克星ItemType.Ring
    

      

    GeovinDuChain.py

    # 责任链模式 Chain of Responsibility
    
    import enum
    
    
    # Item Types:
    # An enum we'll attach to every game object to specify type:
    # Requires Python 3.4 +
    class ItemType(enum.Enum):
       Sword = 0,
       Armor = 1,
       Potion = 2,
       Ring = 3,
       QuestItem = 4,
    
       Undefined = 5
    
    # Equipment Item:
    # For brevity, we'll just use a base class.
    # In a real-world scenario, you'd want to subclass for more abilities.
    class EquipmentItem(object):
       def __init__(self, name, itemType):
           self.name = name
           self.type = itemType
           print(str(self.name)+""+str(self.type)+" 设备细项")
    # Item Chest:
    # A sortage container class:
    class ItemChest(object):
       def __init__(self, name):
          self.chestName = name
          self.items = []
          print(str(self.chestName)+"  项目")
       def putAway(self, item):
          self.items.append(item)
          self.c= len(self.items)
          print("1:"+str(self.c))
       def printItems(self):
          # print(str(self.items.count))
          if self.items.count > 0:   # erro
             print("项目: " + str(self.chestName) + ": ")
             for item in self.items:
                print("\t" + str(item.name))
          else:
             print("empty")
             print(str(self.chestName) + " 是空的项目!")
    
    # Chest Sorter Chain of Responsibility:
    #GeovinDuChain.py
    
    class ChestSorter(object):
       def __init__(self, chest, sortType):
            self.chest = chest
            self.sortType = sortType
            self.next = None
    
       def setNext(self, sorter):
          self.next = sorter
    
       def handle(self, item):
          if item.type == self.sortType:
             self.chest.putAway(item)
             print(" handle")
          elif self.next is not None:
             self.next.handle(item)
    
       def printChain(self):
          # erro
          self.chest.printItems()  # erro
          # self.chest.printItems()
          if self.next is not None:
             self.next.printChain()
    
    
    # The Null sorter gracefully handles a scenario where no item has a fit:
    class NullSorter(ChestSorter):
        def __init__(self, chest):
            super(NullSorter, self).__init__(chest, ItemType.Undefined)
    
    def handle(self, item):
            self.chest.putAway(item)
    

      

    main.py

    调用:

    # 责任链模式 Chain of Responsibility
    wordChest = GeovinDuChain.ItemChest("剑膛")
    armorChest = GeovinDuChain.ItemChest("胸甲")
    potionChest = GeovinDuChain.ItemChest("魔药")
    otherItems = GeovinDuChain.ItemChest("杂项.")
    
    # Create the chain of responsibility:
    
    swords = GeovinDuChain.ChestSorter(swordChest, GeovinDuChain.ItemType.Sword)
    armor = GeovinDuChain.ChestSorter(armorChest, GeovinDuChain.ItemType.Armor)
    potions = GeovinDuChain.ChestSorter(potionChest, GeovinDuChain.ItemType.Potion)
    # Null sorter for item's that don't have an explicit chest:
    other = GeovinDuChain.NullSorter(otherItems)
    
    # Link the chains:
    swords.setNext(armor)
    armor.setNext(potions)
    potions.setNext(other)
    
    # Pointer to the head of the list:
    # Implementation note: You can create another class to maintain all the sorting items!
    sortingMachine = swords
    
    # Insert a few items into the sorting machine:
    sortingMachine.handle(GeovinDuChain.EquipmentItem("强大的剑", GeovinDuChain.ItemType.Sword))
    sortingMachine.handle(GeovinDuChain.EquipmentItem("救命药水", GeovinDuChain.ItemType.Potion))
    sortingMachine.handle(GeovinDuChain.EquipmentItem("无穷之刃", GeovinDuChain.ItemType.Sword))
    sortingMachine.handle(GeovinDuChain.EquipmentItem("护胸垫", GeovinDuChain.ItemType.Armor))
    sortingMachine.handle(GeovinDuChain.EquipmentItem("千经真理卷", GeovinDuChain.ItemType.QuestItem))
    sortingMachine.handle(GeovinDuChain.EquipmentItem("西铎的克星", GeovinDuChain.ItemType.Ring))
    
    # Display all the chests' contents:
    sortingMachine.printChain()
    

      

    输出:

    剑膛  项目
    胸甲  项目
    魔药  项目
    杂项.  项目
    强大的剑ItemType.Sword 设备细项
    1:3
     handle
    救命药水ItemType.Potion 设备细项
    1:1
     handle
    无穷之刃ItemType.Sword 设备细项
    1:4
     handle
    护胸垫ItemType.Armor 设备细项
    1:1
     handle
    千经真理卷ItemType.QuestItem 设备细项
    西铎的克星ItemType.Ring 设备细项
    
    Process finished with exit code 1
    

      

    # 责任链模式 Chain of Responsibility
    
    import enum
    
    
    # Item Types:
    # An enum we'll attach to every game object to specify type:
    # Requires Python 3.4 +
    class ItemType(enum.Enum):
       Sword = 0,
       Armor = 1,
       Potion = 2,
       Ring = 3,
       QuestItem = 4,
       Undefined = 5
    
    # Equipment Item:
    # For brevity, we'll just use a base class.
    # In a real-world scenario, you'd want to subclass for more abilities.
    class EquipmentItem(object):
       def __init__(self, name, itemType):
           self.name = name
           self.type = itemType
           print(str(self.name)+""+str(self.type)+" 设备细项")
    
    
    # Item Chest:
    # A sortage container class:
    class ItemChest(object):
       def __init__(self, name):
           self.chestName = name
           self.items = []
           print(str(self.chestName)+"  项目")
    
       def putAway(self, item):
          self.items.append(item)
          self.c= len(self.items)
          print("1:"+str(self.c))
    
    
       def printItems(self):
          # print(str(self.items.count))
          if self.items.count > 0:   # erro
             print("项目: " + str(self.chestName) + ": ")
             for item in self.items:
                 print("\t" + str(item.name))
          else:
             print("empty")
             print(str(self.chestName) + " 是空的项目!")
    
    
    
    
    
    # Chest Sorter Chain of Responsibility:
    class ChestSorter(object):
       def __init__(self, chest, sortType):
          self.chest = chest
          #self.chest=ItemChest
          self.sortType = sortType
          self.next = None
    
       def setNext(self, sorter):
          self.next = sorter
    
       def handle(self, item):
          if item.type == self.sortType:
             self.chest.putAway(item)
             print(" handle")
          elif self.next is not None:
             self.next.handle(item)
    
       def printChain(self):
         #self.chest.printItems() #上一个类调用方法出问题,偶尔又可显示出来
         print(self.chest)
         if self.next is not None:
             print("下一个:")
             self.next.printChain()
             print(self.chest)
    
    
    # The Null sorter gracefully handles a scenario where no item has a fit:
    class NullSorter(ChestSorter):
        def __init__(self, chest):
            super(NullSorter, self).__init__(chest, ItemType.Undefined)
    
    def handle(self, item):
            self.chest.putAway(item)
    

      

    输出:

    剑膛  项目
    胸甲  项目
    魔药  项目
    杂项.  项目
    强大的剑ItemType.Sword 设备细项
    1:3
     handle
    救命药水ItemType.Potion 设备细项
    1:1
     handle
    无穷之刃ItemType.Sword 设备细项
    1:4
     handle
    护胸垫ItemType.Armor 设备细项
    1:1
     handle
    千经真理卷ItemType.QuestItem 设备细项
    西铎的克星ItemType.Ring 设备细项
    <DuChain.ItemChest object at 0x000001972B94F490>
    下一个:
    <GeovinDuChain.ItemChest object at 0x000001972B94F970>
    下一个:
    <GeovinDuChain.ItemChest object at 0x000001972B94F9D0>
    下一个:
    <GeovinDuChain.ItemChest object at 0x000001972B94FA30>
    <GeovinDuChain.ItemChest object at 0x000001972B94F9D0>
    <GeovinDuChain.ItemChest object at 0x000001972B94F970>
    <DuChain.ItemChest object at 0x000001972B94F490>
    

      

  • 相关阅读:
    安装好php后找不到php.ini
    Nginx 和 PHP 的两种部署方式比较
    高性能Web服务之lnmp架构应用
    >/dev/null 2>&1的含义
    LC_ALL=C的含义
    深入理解PHP Opcode缓存原理
    iostat 监视I/O子系统
    sar 找出系统瓶颈的利器
    Linux常用命令汇总
    linux增加自定义path和manpath
  • 原文地址:https://www.cnblogs.com/geovindu/p/16817844.html
Copyright © 2020-2023  润新知