Design pattern-behavior-template method pattern

Template method pattern

Overview

  • Define the algorithm skeleton in the operation, and delay some steps to the implementation of the subclass, so that a subclass can redefine the specific steps of the algorithm without changing the structure of the algorithm

Object

  • Abstract class: define abstract atomic operations (hook operations); implement a template method as the algorithm skeleton
  • Specific class: realize atomic operation

Applicable scene

  • Implement the invariant part of the algorithm in one go
  • The common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication
  • Control subclass extension

example

"""
设计一个windows程序,桌面开始,绘制,结束

"""
from abc import ABCMeta, abstractmethod
import time

class Windows(metaclass=ABCMeta):
    @abstractmethod
    def start(self): # 原子/钩子操作
        pass
    
    @abstractmethod
    def draw(self):
        pass

    @abstractmethod
    def stop(self):
        pass

    def run(self): # 模板方法
        self.start()
        while True:
            try:
                self.draw()
                time.sleep(1)
            except KeyboardInterrupt:
                break
        self.stop()

class MyWin(Windows):
    def __init__(self, win_info):
        self.win_info = win_info

    def start(self):
        print("windows start...")
    
    def draw(self):
        print(f"draw: {self.win_info}")
    
    def stop(self):
        print("win stop...")

win = MyWin("win info")
win.run()

Guess you like

Origin blog.csdn.net/DALAOS/article/details/114222387