Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Design Patterns @PyCon APAC 2022

Max Lai
August 22, 2022

Python Design Patterns @PyCon APAC 2022

This is the slides of my sharing, "Python Design Pattern," at PyCon APAC 2022.

Max Lai

August 22, 2022

More Decks by Max Lai

Other Decks in Programming


  1. About Me • Max Lai • Senior Manager of Info.

    Tech. Dept. @Tungs' Taichung MetroHarbor Hospital • Tech Lead of Intelligent Healthcare Application • Community • Co-organizer of Taichung.py since June 2014 • Organizer of the Agile Taichung, 2014~2018 • Host of Agile Tour Taichung, 2015~2018
  2. Outline • What Are Design Patterns • Case Study: A

    Reusable Medical Form Module • Design Patterns in Python • Q&A Demo Program : github.com/cclai999/pyconapac22-dp
  3. The Birth of Patterns Each pattern is a three-part rule,

    which express a relation between a certain context, a problem, and a solution.
  4. A pattern is a proven solution to a problem in

    a context. Software Design Pattern Source: https://wiki.c2.com/?PatternDefinitionThread
  5. Why Design Patterns • Design patterns help with reuse and

    communication • Reuse solutions : do not have to reinvent solutions for commonly recurring problems • Establish common terminology : provide a common point of reference during the analysis and design phase of a project • Design patterns give a higher perspective on analysis and design • This frees you from the tyranny of dealing with the details too early Source: Design Patterns Explained: A New Perspective on Object-Oriented Design, 2nd ed.
  6. Design Pattern Descriptions • Name • Intent, problem and context

    • Solution, implementation guidelines • Participants and collaborators • Positive and negative consequences Pattern descriptions are often independent of programming language or implementation details
  7. Design Patterns Catalog <<GOF>> Creational patterns Structural patterns Behavioral patterns

    • Factory Method • Abstract Factory • Builder • Prototype • Singleton • Adapter • Bridge • Composite • Decorator • Facade • Flyweight • Proxy • Chain of Responsibility • Interpreter • Iterator • Mediator • Memento • Observer • State • Strategy • Template Method • Visitor
  8. Principles for Creating Good OO Design • Program to an

    interface, not an implementation • Favor object composition over class inheritance
  9. Thinking in Design Patterns • Context first (design from context)

    • Building by adding distinctions • One pattern at a time • Encapsulate variations in classes Source: Design Patterns Explained: A New Perspective on Object-Oriented Design, 2nd ed.
  10. Workers’ Physical and Health Examination Record Form • Workers’ Physical

    and Health Examination Record Form 勞工一般/特殊特殊體格及健康檢查紀錄 • Occupational Safety and Health Administration, Ministry of Labor (勞 動部職業安全衛生署) • https://www.osha.gov.tw/1106/29647/1141/13440/ • There are total 33 forms in this case • In fact, there are thousands of forms in a hospital
  11. Sample Form in Case Study 勞⼯⼀般體格及健康檢查紀錄 1.姓名:__________ 2.性別:□男 □⼥ 3.檢查日期:___年___月___日

    4.是否需輪班: □是 ( □兩班制 □三班制 □四班制 □其他:_____ ) □否 5.您是否曾患有下列慢性疾病:(請在適當項目前打勾) □⾼⾎壓 □糖尿病 □⼼臟病 □癌症____ □其他慢性病____ □以上皆無
  12. Composite Pattern • Compose objects into tree structures to represent

    part-whole hierarchies. • Composite lets clients treat individual objects and compositions of objects uniformly.
  13. Factory Method • Define an interface for creating an object,

    • but let subclasses decide which class to instantiate. • Defer instantiation to subclasses.
  14. Call factory to create “Sheet” object Call factory to create

    “InputText” object Call factory to create “CheckGroup” object Append to input_items “Option” object Append to input_items “Option” object
  15. Output JSON Data The backend send JSON data to the

    frontend Form rendered by Vue.js
  16. Mixin • Use Mixins for Code Reuse • a mixin

    does not define a new type; • it merely bundles methods for reuse • Make Mixins Explicit by Naming • named with a ...Mixin suffix • e.g. JsonMixin in case study
  17. Output Text Format • People may not be able to

    connect to our website at the corporate medical examination site. • We need a paper form in this case.
  18. Visitor Pattern • Represent an operation to be performed on

    the elements of an object structure. • Visitor lets you define a new operation without changing the classes of the elements on which it operates.
  19. Visitor Pattern ① ② ③ ④ ⑬ ⑫ ⑪ ⑩

    ⑨ ⑧ ⑦ ⑥ ⑤ ⑲ ⑱ ⑰ ⑯ ⑮ ⑭ ⑳ ㉑
  20. Output Text by Visitor 勞工一般體格及健康檢查紀錄 姓名: _______ 性別[單選]:( )男( )女

    檢查日期:___年___月___日 是否需輪班[單選]: ( )是[單選]:( )兩班制( )三班制( )四班制( )其他 _______ ( )否 您是否曾患有下列慢性疾病[多選]: 【 】高血壓 【 】糖尿病 【 】心臟病 【 】癌症 _______ 【 】以上皆無
  21. Design Pattern in Dynamic Languages • Peter Norvig states that

    16 out of the 23 patterns in the original Design Patterns book become either “invisible or simpler” in a dynamic language (slide 9) • “Design Patterns in Dynamic Languages” (1996) Source: http://norvig.com/design-patterns/design-patterns.pdf
  22. First Class Object • Functions in Python are first-class objects.

    • A “first-class object” as a program entity that can be: • created at runtime; • assigned to a variable or element in a data structure; • passed as an argument to a function; • returned as the result of a function. Source: Fluent Python, 2nd edition
  23. Function-Oriented Strategy “”“5% discount for customers with 1000 or more

    fidelity points""" """10% discount for each LineItem with 20 or more units""" """7% discount for orders with 10 or more distinct items"""
  24. Modules are “Singletons” in Python • import only creates a

    single copy of each module • subsequent imports of the same name keep returning the same module object • Official Python FAQ[1]: using a module is also the basis for implementing the Singleton design pattern, for the same reason. [1] https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
  25. Key Takeaways What • Have a context • Solve a

    problem • Recur • Have a name Why • Reuse solutions • Establish common terminology • Give a higher perspective on design How • Context first • One pattern at a time • Encapsulate variations