search
HomeBackend DevelopmentPython TutorialPython's combination mode and chain of responsibility mode programming examples

Composite mode
We regard the Composite mode as a complex attribute structure. In fact, there are basically three roles: trunk (define some operations to operate leaves), branches (there are many branches on the trunk) and leaves (think trunk) Objects to be manipulated), the Composite pattern helps us realize: that is, when they act as objects, they are still as easy as other objects, thus providing consistency

python example

class Trunk(object):
  '''树干'''
  def __str__(self):
    pass
 
  def subtree(self):
    pass
 
class Composite(Trunk):
  def __init__(self, left=None, right=None, length=None):
    self.left=left
    self.right=right
    self.length=length
 
  def __str__(self):
    # 这个结果是在调用subtree()的时候返回
    if self.length:
      return "(" + self.left.__str__() + ", " + self.right.__str__() + ")" + ": " + str(self.length)
    else:
      return "(" + self.left.__str__() + ", " + self.right.__str__() + ")"
 
    # 这里其实就是一个技巧,通过这个函数返回下一级的对象,也就是它既是对象还可以是对象的容器
    def subtree(self):       
      return Composite(self.left, self.right)
 
class Leaf(Trunk):
  '''叶子类,它没办法继续延伸了'''
  def __init__(self, name, length=None):
    self.name = name
    self.length=length
    self.left = None
    self.right = None
 
  def __str__(self):
    return self.name + ": " + str(self.length)
 
  def subtree(self):
    return Leaf(self.name, self.length)
 
 
if __name__ == "__main__":
  # 只有叶子那么就直接返回__str__的拼装结果
  t1 = Leaf('A', 0.71399)
  print t1
  # 有个2个叶子的组合,返回的是2个叶子的对象的组合
  t2 = Composite(Leaf('B', -0.00804),
    Leaf('C', 0.07470))
  print t2
  # 这个是嵌套的叶子的组合,树干上面有树枝,树枝上面有叶子
  t3 = Composite(Leaf('A', 0.71399),
    Composite(Leaf('B', -0.00804),
        Leaf('C', 0.07470), 0.1533), 0.0666)
 
  print t3
  # 直接通过左右节点找到对应的叶子对象了
  t4 = t3.right.right.subtree()
  print t4
  # t3的左树其实就是叶子对象了
  t5 = t3.left.subtree()
  print t5


Chain of Responsibility Model
For example, when we were still studying, the test scores were in several grades, such as 90-100 points, 80-90 points, okay I think Make a feedback that prints your academic performance based on the scores. For example, 90-100 is A+, 80-90 is A, 70-80 is B+... Of course, you can use many methods to achieve it. I will implement a Chain mode here: use A series of classes to respond, but only when it encounters a class suitable for processing it will be processed, similar to the role of case and switch

python example

class BaseHandler:
  # 它起到了链的作用
  def successor(self, successor):
    self.successor = successor
 
class ScoreHandler1(BaseHandler):
  def handle(self, request):
    if request > 90 and request <= 100:
      return "A+"
    else:
      # 否则传给下一个链,下同,但是我是要return回结果的
      return self.successor.handle(request)
 
class ScoreHandler2(BaseHandler):
  def handle(self, request):
    if request > 80 and request <= 90:
      return "A"
    else:
      return self.successor.handle(request)
 
class ScoreHandler3(BaseHandler):
  def handle(self, request):
    if request > 70 and request <= 80:
      return "B+"
    else:
      return "unsatisfactory result"
 
class Client:
  def __init__(self):
    h1 = ScoreHandler1()
    h2 = ScoreHandler2()
    h3 = ScoreHandler3()
    # 注意这个顺序,h3包含一个类似于default结果的东西,是要放在最后的,其他的顺序是无所谓的,比如h1和h2
    h1.successor(h2)
    h2.successor(h3)
 
    requests = {&#39;zhangsan&#39;: 78,
          &#39;lisi&#39;: 98,
          &#39;wangwu&#39;: 82,
          &#39;zhaoliu&#39;: 60}
    for name, score in requests.iteritems():
      print &#39;{} is {}&#39;.format(name, h1.handle(score))
 
if __name__== "__main__":
  client = Client()

For more articles related to Python’s combination mode and chain of responsibility mode programming examples, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use