---
title: "CP4 - Prototype - Học Design Pattern Từ Những Thứ Đơn Giản"
description: "Con robot gắn bó lâu năm có đầy ký ức mà dây chuyền bình thường không sản xuất được. Tìm hiểu Prototype trong Python và lỗi deepcopy kinh điển."
pubDate: "2022-12-18"
lang: "vi"
slug: "cp4-prototype-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/vi/cp4-prototype-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_en: "https://hoangyell.com/cp4-prototype-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "creational-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/syNmmBu.webp"
---

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

## Prototype là gì?

Prototype là kỹ thuật giúp nhân bản (clone) một object có sẵn thay vì khởi tạo lại từ đầu.

![Image](https://raw.githubusercontent.com/HoangGeek/store/main/webp/208253852-a6e3f152-9846-4855-8161-ef23abe97c2e.webp)

```markdy
scene duration=18 layout=LR width=1280 height=720
theme: light=doodle dark=nebula

service Origin "OriginRobot (id=200 <-> memory)" icon=python
gateway CopyMod "Module copy của Python" icon=python
service Shallow "copy.copy (dùng chung ruột)"
service Deep "copy.deepcopy (tách hẳn + memo dict)"

beat shallow "1. Shallow copy dùng chung tham chiếu":
  show $nodes stagger=50ms
  Origin -> CopyMod "copy.copy(robot)"
  CopyMod -> Shallow "Sửa list bên này, bên kia dính theo"
  glow Shallow color=#f59e0b

beat deep "2. Deepcopy xử lý chuẩn tham chiếu vòng":
  Origin -> CopyMod "copy.deepcopy(robot)"
  CopyMod -> Deep "memo[id] giữ đúng liên kết vòng"
  glow Deep 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 Prototype?
- Để copy nguyên xi một object đang có.
- Thực tế bạn **không cần học Prototype kiểu GoF trong Python**, vì module `copy` tích hợp sẵn làm hết việc này rồi.
  - Mọi object trong Python đều clone được bằng `copy`.
  - Lưu ý: ví dụ ghi đè `def __deepcopy__` trên [refactoring.guru](https://refactoring.guru/design-patterns/prototype/python/example) vừa rườm rà vừa **sai logic**. Đừng copy theo họ, cứ dùng thẳng module `copy` chuẩn của Python.

**Hỏi:** _Vậy... bài blog này viết ra để làm gì?_

**Đáp:** _Để bạn biết là không cần cày Prototype trong Python, đọc xong rồi nhảy qua pattern tiếp theo cho nhanh._

![Image](https://y.yarn.co/c7731c16-7490-416e-84e8-9c6b5158b71d_text.gif)

## Khi nào dùng Prototype?

**Hỏi:** _Khi nào thì tôi đang dùng Prototype?_

**Đáp:** _Mỗi lần bạn gọi `copy.copy` hoặc `copy.deepcopy`, chính là bạn đang dùng Prototype rồi._

### Đầu vào:
  - Có sẵn một object gốc `Robot`
  - Tạo bản sao `copied_robot` từ `origin_robot`:
    - Dùng (shallow) `copy`:
      - `copied_robot.mutable` ↔️ dùng chung tham chiếu với `origin_robot.mutable`
    - Dùng `deepcopy`:
      - `copied_robot.mutable` 🛡️ tách độc lập hoàn toàn với `origin_robot.mutable`

[Đọc thêm về mutable và immutable trong Python](https://www.mygreatlearning.com/blog/understanding-mutable-and-immutable-in-python)

``` python
import copy

class MemoryRobot:
    def __init__(self):
        self.who_am_i = None

    def set_memory(self, who_am_i):
        self.who_am_i = who_am_i

class Robot:
    def __init__(self, age, body_parts, memory):
        self.age = age
        self.body_parts = body_parts
        self.memory = memory

    @property
    def id(self):
        # https://www.digitalocean.com/community/tutorials/python-id
        return str(id(self))[-3:]

if __name__ == "__main__":

    def init_robot():
        robot_body_parts = [
            "head",
            {"left hand", "chest", "right hand"},
            ["left foot", "butt", "right foot"],
        ]
        memory_robot = MemoryRobot()
        robot = Robot(18, robot_body_parts, memory_robot)
        memory_robot.set_memory(robot)
        return robot

    def copy_robot(origin_robot, copy_method):
        wing = "wing"
        tail = "tail"
        tab = "    "
        tab_2 = "    " * 2
        tab_3 = "    " * 3
        print(f"\nCopying by {copy_method.__name__}:")
        copied_robot = copy_method(origin_robot)
        copied_robot.body_parts.append(tail)
        is_origin_robot_changed = origin_robot.body_parts[-1] == tail
        print(f"{tab}Question: update copied_robot changes origin_robot?")
        print(f"{tab_2}Answer: {is_origin_robot_changed}")

        origin_robot.body_parts[1].add(wing)
        is_copied_robot_changed = wing in copied_robot.body_parts[1]
        print(f"{tab}Question: update origin_robot changes copied_robot?")
        print(f"{tab_2}Answer: {is_copied_robot_changed}")

        print(f"{tab}How about reference?")
        print(f"{tab_2}origin_robot reference:")
        print(f"{tab_3}{origin_robot.id} is the ID of origin_robot")
        print(
            f"{tab_3}{origin_robot.memory.who_am_i.id} is the ID of origin_robot.memory.who_am_i"
        )
        print(f"{tab_2}copied_robot reference:")
        print(f"{tab_3}{copied_robot.id} is the ID of copied_robot")
        print(
            f"{tab_3}{copied_robot.memory.who_am_i.id} is the ID of copied_robot.memory.who_am_i"
        )
        return copied_robot

    origin_robot_1 = init_robot()
    shallow_copied_robot = copy_robot(origin_robot_1, copy.copy)

    origin_robot_2 = init_robot()
    deep_copied_robot = copy_robot(origin_robot_2, copy.deepcopy)
```

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

``` shell
Copying by copy:
    Question: update copied_robot changes origin_robot?
        Answer: True
    Question: update origin_robot changes copied_robot?
        Answer: True
    How about reference?
        origin_robot reference:
            100 is the ID of origin_robot
            100 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            101 is the ID of copied_robot
            100 is the ID of copied_robot.memory.who_am_i

Copying by deepcopy:
    Question: update copied_robot changes origin_robot?
        Answer: False
    Question: update origin_robot changes copied_robot?
        Answer: False
    How about reference?
        origin_robot reference:
            200 is the ID of origin_robot
            200 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            201 is the ID of copied_robot
            201 is the ID of copied_robot.memory.who_am_i
```

## So sánh cách triển khai:

### Cách viết sai trên Refactoring.guru:
``` python
class Robot:
    ...

    def __copy__(self):
        body_parts = copy.copy(self.body_parts)
        memory = copy.copy(self.memory)
        copied_robot = self.__class__(self.age, body_parts, memory)
        copied_robot.__dict__.update(self.__dict__)
        return copied_robot

    def __deepcopy__(self, _=None):
        if _ is None:
            _ = {}
        body_parts = copy.deepcopy(self.body_parts, _)
        memory = copy.deepcopy(self.memory, _)
        copied_robot = self.__class__(self.age, body_parts, memory)
        copied_robot.__dict__ = copy.deepcopy(self.__dict__, _)
        return copied_robot
    ...
```
Cách viết này sai ở đoạn `deepcopy`:
- `copied_robot` ID là `401` nhưng `copied_robot.memory.who_am_i` lại có ID `402` (khác nhau!).
- Lý do: Nó tạo `copied_robot` mà **quên đăng ký `_[id(self)] = copied_robot` vào memo dict** trước khi `deepcopy` `self.memory`, làm tham chiếu vòng (`circular reference`) đẻ ra thêm một bản `Robot` thừa.

```shell
Copying by copy:
    Question: update copied_robot changes origin_robot?
        Answer: True
    Question: update origin_robot changes copied_robot?
        Answer: True
    How about reference?
        origin_robot reference:
            300 is the ID of origin_robot
            300 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            301 is the ID of copied_robot
            300 is the ID of copied_robot.memory.who_am_i

Copying by deepcopy:
    Question: update copied_robot changes origin_robot?
        Answer: False
    Question: update origin_robot changes copied_robot?
        Answer: False
    How about reference?
        origin_robot reference:
            400 is the ID of origin_robot
            400 is the ID of origin_robot.memory.who_am_i
        copied_robot reference:
            401 is the ID of copied_robot
            402 is the ID of copied_robot.memory.who_am_i
```

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

### Cách triển khai Prototype chuẩn trong Python:
Bạn đang dùng nó ở phần **Đầu vào** với `copy.deepcopy` sẵn rồi, không cần viết thêm dòng nào!
``` python
# nothing here
```

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

***

**Điều hướng series:** Trước: [CP3 - Builder](https://hoangyell.com/vi/cp3-builder-design-pattern-from-simple-things/) · Tiếp theo: [CP5 - Singleton](https://hoangyell.com/vi/cp5-singleton-learn-design-pattern-from-simple-things/)
