---
title: "BP7 - Khung Mẫu (Template Method) - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Volkswagen giữ chung dây chuyền lắp ráp cho Lamborghini và Porsche nhưng cho tùy biến động cơ và khung gầm. Học Template Method bằng Python."
pubDate: "2023-04-01"
lang: "vi"
slug: "bp7-template-method-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/bp7-template-method-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/bp7-template-method-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/photo-1573950940509-d924ee3fd345.webp"
---

_Template Method là một mẫu thiết kế nhóm **Behavioral**:_
🖤🖤🖤🖤🖤 *(Độ hữu dụng trong Python: 5/5)*

## Template Method là gì?

Template Method cho phép class cha định nghĩa sẵn bộ khung (trình tự các bước) của một quy trình, còn chi tiết từng bước để class con tự triển khai hoặc ghi đè lại. Ví dụ tập đoàn mẹ `Volkswagen` khóa cứng quy trình lắp xe gồm `install_engine -> assemble_chassis -> paint_body`, còn `Lamborghini` và `Porsche` tự lắp động cơ theo gu của mình.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/229270478-44b33811-d007-4e7d-9154-2de922ddd70a.webp)

```markdy
scene duration=18 layout=TB width=760 height=960
theme: light=doodle dark=nebula

service Base "Volkswagen.manufacture_car() [Khung chuẩn]" icon=python
service Steps "1. install_engine -> 2. assemble_chassis -> 3. paint_body"
service Lambo "Lamborghini (độ máy + độ khung)"
service Porsche "Porsche (độ máy, giữ nguyên khung/sơn VW)"

beat lock "1. Class cha khóa cứng trình tự 3 bước":
  show $nodes stagger=50ms
  Base -> Steps "Ép chạy đúng thứ tự"
  glow Base color=#3b82f6

beat override "2. Class con chỉ override bước cần đổi":
  Steps -> Lambo "Máy gầm + khung khí động học"
  Steps -> Porsche "Máy êm + giữ nguyên khung VW"
  glow Lambo color=#22c55e
  glow Porsche color=#22c55e

player:
  playback:
    loop true
  controls:
    speed true
    speeds "0.25"
    interact true
    fullscreen true
    gif true
    theme true
  interaction:
    zoom true
    pan true
    click_to_play true
    double_click_to_reset true
    keyboard false
  chrome:
    badge true
    progress none
```

## Tại sao dùng Template Method?
- **Khóa thứ tự các bước, mở cho tùy biến chi tiết**: `Volkswagen.manufacture_car()` đảm bảo quy trình không bao giờ chạy sai thứ tự, trong khi `Lamborghini` và `Porsche` chỉ phải override đúng bước cần khác biệt.
- **Đánh đổi**: Nó dựa vào kế thừa nên class con dính chặt vào class cha. Nếu từng bước thay đổi độc lập nhiều, ưu tiên composition hơn inheritance.

**Hỏi:** _Tôi ghét Template Method, có cách nào khác không?_

**Đáp:** _Dùng **Dependency Injection / Composition**: truyền thẳng `engine`, `chassis`, `body` (hoặc truyền từng hàm xử lý) vào `Volkswagen.__init__` thay vì đẻ class con. Nhìn bản `Không dùng Template Method` bên dưới xem nó ngắn hơn bản kế thừa thế nào!_

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/vwDbM0w.webp)

## Khi nào dùng Template Method?

**Hỏi:** _Khi nào tôi nên dùng Template Method?_

**Đáp:** _Khi nhiều class chạy cùng một quy trình cố định nhiều bước và chỉ khác nhau ở một vài bước cụ thể bên trong._

### Đầu vào:

``` python
class Volkswagen:
    def manufacture_car(self):
        self.install_engine()
        self.assemble_chassis()
        self.paint_body()

    def install_engine(self):
        raise NotImplementedError

    def assemble_chassis(self):
        print("Assembling a Volkswagen chassis")

    def paint_body(self):
        print("Painting the body with Volkswagen color")

class Lamborghini(Volkswagen):
    def install_engine(self):
        print("Installing a powerful and loud engine")

    def assemble_chassis(self):
        print("Assembling a lightweight and aerodynamic chassis")

class Porsche(Volkswagen):
    def install_engine(self):
        print("Installing a fast and smooth engine")
```

### Kết quả mong muốn:

``` shell
Manufacturing Lamborghini:
Installing a powerful and loud engine
Assembling a lightweight and aerodynamic chassis
Painting the body with Volkswagen color

Manufacturing Porsche:
Installing a fast and smooth engine
Assembling a Volkswagen chassis
Painting the body with Volkswagen color
```

## Triển khai Template Method:

### Cách viết không dùng Template Method (Dependency Injection):

Truyền thẳng cấu hình `engine`, `chassis`, `body` vào `Volkswagen.__init__` mà không cần tạo subclass.

``` python
class Volkswagen:
    def __init__(self, engine, chassis="Volkswagen", body="Volkswagen"):
        self.engine = engine
        self.chassis = chassis
        self.body = body

    def manufacture_car(self):
        self.install_engine()
        self.assemble_chassis()
        self.paint_body()

    def install_engine(self):
        print(f"Installing a {self.engine} engine")

    def assemble_chassis(self):
        print(f"Assembling a {self.chassis} chassis")

    def paint_body(self):
        print(f"Painting the body with {self.body} color")

if __name__ == "__main__":
    print("Manufacturing Lamborghini:")
    lamborghini = Volkswagen(
        engine="powerful and loud", chassis="lightweight and aerodynamic"
    )
    lamborghini.manufacture_car()
    print("\n")

    print("Manufacturing Porsche:")
    porsche = Volkswagen(engine="fast and smooth")
    porsche.manufacture_car()
```

### Cách viết dùng Template Method:

Class trừu tượng `Volkswagen` khóa quy trình trong `manufacture_car()`, ép class con cài đặt `install_engine()` nhưng giữ sẵn logic mặc định cho `assemble_chassis()` và `paint_body()`.

``` python
from abc import ABC, abstractmethod

class Volkswagen(ABC):
    """The Abstract Class defines a template method that contains a skeleton of
    some algorithm, composed of calls to (usually) abstract primitive operations.

    Concrete subclasses should implement these operations, but leave the template
    method itself intact.
    """

    def manufacture_car(self) -> None:
        """The template method defines the skeleton of an algorithm."""
        self.install_engine()
        self.assemble_chassis()
        self.paint_body()

    @abstractmethod
    def install_engine(self) -> None:
        pass

    def assemble_chassis(self) -> None:
        print("Assembling a Volkswagen chassis")

    def paint_body(self) -> None:
        print("Painting the body with Volkswagen color")

class Lamborghini(Volkswagen):
    def install_engine(self) -> None:
        print("Installing a powerful and loud engine")

    def assemble_chassis(self) -> None:
        print("Assembling a lightweight and aerodynamic chassis")

class Porsche(Volkswagen):
    def install_engine(self) -> None:
        print("Installing a fast and smooth engine")

if __name__ == "__main__":
    print("Manufacturing Lamborghini:")
    lamborghini = Lamborghini()
    lamborghini.manufacture_car()
    print("\n")

    print("Manufacturing Porsche:")
    porsche = Porsche()
    porsche.manufacture_car()
```

Dùng **Template Method** khi muốn ép chặt hợp đồng kế thừa (`@abstractmethod`) trên một quy trình nhiều bước cố định; còn chỉ để thay đổi tham số hay hành vi nhẹ nhàng thì **Dependency Injection** ở trên gọn hơn nhiều.

[Source Code](https://github.com/HoangYell/Design-Pattern-From-Simple-Things/blob/main/bp7_template_method.py)

***

**Điều hướng series:** Trước: [BP6 - State](https://hoangyell.com/vi/bp6-state-learn-design-pattern-from-simple-things/) · Tiếp theo: [BP8 - Visitor](https://hoangyell.com/vi/bp8-visitor-learn-design-pattern-from-simple-things/)
