首页 > 编程语言 >Python: Chain of Responsibility

Python: Chain of Responsibility

时间:2022-10-23 08:33:20浏览次数:59  
标签:ItemType Chain DuChain Python self item Responsibility class def

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

  

 

标签:ItemType,Chain,DuChain,Python,self,item,Responsibility,class,def
From: https://www.cnblogs.com/geovindu/p/16817844.html

相关文章

  • 解决python包含中文运行报错问题,报错信息SyntaxError: Non-UTF-8 code starting with
    运行以下python文件报错,提示:SyntaxError:Non-UTF-8codestartingwith'\xce'in...  在第一行加上:#coding=gbk就可以了。  ......
  • Python学习三天计划-3
    面向对象一、类的定义1.类定义class是关键字,表示要定义类了类的属性,即定义在类中的变量(成员变量)类的行为,即定义在类中的函数(成员方法)2.对象创建类对象的语法:cl......
  • 【记录】创建linux开发python环境
    安装GCCER之类的东西sudoaptinstallbuild-essentialubantu20.4不需要这句sudoaptinstallpython3.8下载minicondawgethttps://repo.anaconda.com/miniconda/M......
  • Python自动化库之pywinauto
    简介pywinauto是python在windows环境下自动化操作图形应用的第三方库。支持鼠标和键盘操作,获取文本数据等。github地址:https://github.com/pywinauto/pywinauto官方说......
  • Python元类详解
    目录PythonMetaClass一、万物皆对象1、简介2、Python对象3、type|object|class3.1关系3.2创建类的第二中方式二、元类1、什么是元类2、调用流程3、函数做元类4......
  • Python: Proxy Pattern
     DuProxy.py#代理模式ProxyPatternfromabcimportABCMeta,abstractmethodimportabcimportrandomclassISubject(metaclass=ABCMeta):"Aninterface......
  • GPU编程实战:基于Python和CUDA 电子书 pdf
    作者:布莱恩·图奥迈宁(BrianTuomanen)出版社:人民邮电出版社原作名:Hands-OnGPUProgrammingwithPythonandCUDA 链接:GPU编程实战:基于Python和CUDA  本书......
  • 30 个 Python 技巧,加速你的数据分析处理速度
    pandas的下载 使用命令下载:pipinstallpandas  或者自行下载whl文件安装https://www.lfd.uci.edu/~gohlke/pythonlibs/  创建DataFrame数据pd_da......
  • python 调用Adobe Acrobat 将pdf 转 excel
    最近需要批量转换一些pdf扫描件,就开始找相关的python包花了不少时间试了下pdfplumber,pypdf2,camelot这几个包发现都不能成功的转化,原因就在于手上的pdf是扫描件,......
  • python的字符串截取
    截取规则:实际Python字符串截取的规则为“前闭后开”简单规律总结:字符串截取一般有两种形式[:]这种形式就是从哪截取到哪里如果是负数就从后往前找[::]这种......