Slide 1

Slide 1 text

Max Lai PyCon APAC 2022 Python Design Patterns

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

What Are Design Patterns

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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.

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

Draw All Shape (POP)-2

Slide 13

Slide 13 text

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

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

Draw All Shape (OOP)-2

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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

Slide 18

Slide 18 text

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.

Slide 19

Slide 19 text

Case Study: A Reusable Medical Form Module

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

OSHA- Examination Record Form List

Slide 22

Slide 22 text

Form Example 1

Slide 23

Slide 23 text

Form Example 2

Slide 24

Slide 24 text

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

Slide 25

Slide 25 text

Thinking in DP: Context First

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

Thinking in DP: Encapsulate variations in classes Composite Pattern

Slide 28

Slide 28 text

Composite Pattern

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

Transform YAML Data to Composite Objects

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

Factory Method

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

① ② ③ ④ ⑤ Transform composite objects to JSON data

Slide 35

Slide 35 text

Output JSON Data add additional function by Mixin

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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.

Slide 38

Slide 38 text

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.

Slide 39

Slide 39 text

Visitor Pattern ① ② ③ ④ ⑬ ⑫ ⑪ ⑩ ⑨ ⑧ ⑦ ⑥ ⑤ ⑲ ⑱ ⑰ ⑯ ⑮ ⑭ ⑳ ㉑

Slide 40

Slide 40 text

Visitor Pattern

Slide 41

Slide 41 text

InputText visit_InputText

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

Design Patterns in Python

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

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

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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

Slide 49

Slide 49 text

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

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

References

Slide 52

Slide 52 text

Thanks Taichung.py