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

  

 

原文地址:http://www.cnblogs.com/geovindu/p/16817844.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性