Home Backend Development Python Tutorial Python's combination mode and chain of responsibility mode programming examples

Python's combination mode and chain of responsibility mode programming examples

Jan 19, 2017 pm 05:06 PM

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
Copy after login


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()
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

See all articles