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
Tweet

More Decks by Max Lai

Other Decks in Programming

Transcript

  1. Max Lai
    PyCon APAC 2022
    Python Design Patterns

    View full-size slide

  2. 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

    View full-size slide

  3. 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

    View full-size slide

  4. What Are Design Patterns

    View full-size slide

  5. The Birth of Patterns
    Each pattern is a three-part rule,
    which express a relation
    between a certain context, a
    problem, and a solution.

    View full-size slide

  6. A pattern is a proven solution
    to a problem
    in a context.
    Software Design Pattern
    Source: https://wiki.c2.com/?PatternDefinitionThread

    View full-size slide

  7. 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.

    View full-size slide

  8. 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

    View full-size slide

  9. Design Patterns Catalog <>
    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

    View full-size slide

  10. Planning for Change
    • The Open/Closed Principle
    • open for extension
    • closed for modification

    View full-size slide

  11. Draw All Shape (POP)-1
    If we want to add another shape class?

    View full-size slide

  12. Draw All Shape (POP)-2

    View full-size slide

  13. Draw All Shape (OOP)-1
    Encapsulate
    Interface – “draw()”
    In an abstract in class

    View full-size slide

  14. Draw All Shape (OOP)-3
    Implement
    another concrete class

    View full-size slide

  15. Draw All Shape (OOP)-2

    View full-size slide

  16. Draw All Shape (OOP)-2
    You don’t need to modify existing codes.

    View full-size slide

  17. Principles for Creating Good OO Design
    • Program to an interface, not an implementation
    • Favor object composition over class inheritance

    View full-size slide

  18. 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.

    View full-size slide

  19. Case Study:
    A Reusable Medical Form Module

    View full-size slide

  20. 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

    View full-size slide

  21. OSHA- Examination Record Form List

    View full-size slide

  22. Form Example 1

    View full-size slide

  23. Form Example 2

    View full-size slide

  24. Sample Form in Case Study
    勞⼯⼀般體格及健康檢查紀錄
    1.姓名:__________
    2.性別:□男 □⼥
    3.檢查日期:___年___月___日
    4.是否需輪班:
    □是 ( □兩班制 □三班制 □四班制 □其他:_____ )
    □否
    5.您是否曾患有下列慢性疾病:(請在適當項目前打勾)
    □⾼⾎壓 □糖尿病 □⼼臟病 □癌症____ □其他慢性病____ □以上皆無

    View full-size slide

  25. Thinking in DP:
    Context First

    View full-size slide

  26. Composite Pattern
    • Compose objects into tree structures to represent part-whole
    hierarchies.
    • Composite lets clients treat individual objects and
    compositions of objects uniformly.

    View full-size slide

  27. Thinking in DP:
    Encapsulate variations in classes
    Composite
    Pattern

    View full-size slide

  28. Composite Pattern

    View full-size slide

  29. Factory Method
    • Define an interface for creating an object,
    • but let subclasses decide which class to instantiate.
    • Defer instantiation to subclasses.

    View full-size slide

  30. Transform YAML Data to Composite Objects

    View full-size slide

  31. 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

    View full-size slide

  32. Factory Method

    View full-size slide

  33. Output JSON Data
    The backend send JSON data
    to the frontend
    Form rendered by Vue.js

    View full-size slide






  34. Transform composite objects
    to JSON data

    View full-size slide

  35. Output JSON Data add additional function by Mixin

    View full-size slide

  36. 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

    View full-size slide

  37. 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.

    View full-size slide

  38. 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.

    View full-size slide

  39. Visitor Pattern

















    ⑮ ⑭


    View full-size slide

  40. Visitor Pattern

    View full-size slide

  41. InputText
    visit_InputText

    View full-size slide

  42. Output Text by Visitor
    勞工一般體格及健康檢查紀錄
    姓名: _______
    性別[單選]:( )男( )女
    檢查日期:___年___月___日
    是否需輪班[單選]:
    ( )是[單選]:( )兩班制( )三班制( )四班制( )其他 _______
    ( )否
    您是否曾患有下列慢性疾病[多選]:
    【 】高血壓
    【 】糖尿病
    【 】心臟病
    【 】癌症 _______
    【 】以上皆無

    View full-size slide

  43. Design Patterns in Python

    View full-size slide

  44. 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

    View full-size slide

  45. 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

    View full-size slide

  46. Strategy pattern
    Source: Fluent Python, 2nd ed., Ch.10

    View full-size slide

  47. 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"""

    View full-size slide

  48. Function-Oriented Strategy
    function as an element in List “promos”

    View full-size slide

  49. 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

    View full-size slide

  50. 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

    View full-size slide

  51. Thanks
    Taichung.py

    View full-size slide