Python: Chain of Responsibility
DuChain.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | # 责任链模式 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 调用:、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | # 责任链模式 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) |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 这是 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | # 责任链模式 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
调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # 责任链模式 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() |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 剑膛 项目 胸甲 项目 魔药 项目 杂项. 项目 强大的剑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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | # 责任链模式 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) |
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 剑膛 项目 胸甲 项目 魔药 项目 杂项. 项目 强大的剑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 > |
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2012-10-23 Csharp: winform PDF view control use Adobe Reader X
2009-10-23 cookieLibrary.js 写入cookie的JavaScript代码库