2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで構築するPrototypeパターン:オブジェクトの複製を制御する設計技法

Posted at

概要

Prototype(プロトタイプ)パターンは、
既存のオブジェクトを元に、同じ構造・状態を持つ新しいオブジェクトを複製することを目的とした設計パターンである。

コンストラクタを経由せずにインスタンスを複製することで、
初期化コストの削減、動的なオブジェクト生成、テンプレートからの派生構築が可能になる。

Pythonの copy モジュールとダックタイピングの特性により、柔軟かつシンプルに実装可能である。


1. なぜPrototypeが必要か?

❌ 毎回同じ初期化処理を走らせる非効率構造

def make_user():
    user = User()
    user.set_default()
    user.connect_to_db()
    return user

→ 同じ設定・構造をもつオブジェクトが必要なだけなのに、毎回初期化コストが高い


✅ 一度作成した「プロトタイプ」から複製

admin_user = prototype.clone()

状態や構造を保持したまま、高速で複製可能


2. Pythonによる基本構造

✅ ベースクラスと clone 実装

import copy

class Prototype:
    def clone(self):
        return copy.deepcopy(self)

✅ 利用例

class User(Prototype):
    def __init__(self, role, permissions):
        self.role = role
        self.permissions = permissions

    def __repr__(self):
        return f"<User {self.role}: {self.permissions}>"
admin = User("admin", ["read", "write", "delete"])
guest = admin.clone()
guest.role = "guest"
guest.permissions = ["read"]

print(admin)  # <User admin: ['read', 'write', 'delete']>
print(guest)  # <User guest: ['read']>

オブジェクトの構造をそのまま複製し、特定の差分だけを変更


3. プロトタイプレジストリの導入

class PrototypeRegistry:
    def __init__(self):
        self._prototypes = {}

    def register(self, key, prototype):
        self._prototypes[key] = prototype

    def clone(self, key):
        return self._prototypes[key].clone()
registry = PrototypeRegistry()
registry.register("admin", User("admin", ["all"]))
registry.register("viewer", User("viewer", ["read"]))

u1 = registry.clone("admin")
u2 = registry.clone("viewer")

テンプレート的に再利用できるプリセットを定義可能


4. 実務ユースケース

✅ GUIコンポーネントのテンプレート複製

→ ボタン・パネル・カードなどのUI要素を高速生成


✅ システム構成や設定の派生構築

→ configベースのオブジェクト設計にて共通定義 + 差分定義


✅ ゲーム開発:キャラやアイテムのベースモデル複製

→ 全く同じ性能や挙動を持つが、識別子や位置だけ異なるエンティティ生成に有効


5. よくある誤用と対策

copy.copy() で浅いコピーをしてしまう

→ ✅ 深い構造を持つ場合は copy.deepcopy() を必ず使用


❌ cloneメソッドを持たないクラスをPrototype扱い

→ ✅ インタフェース(あるいはABC)として clone() の存在を保証


❌ 状態が揮発的・外部依存が強い場合にそのまま複製

→ ✅ クローン対象を明確にし、共有すべきでない状態は除外 or 再初期化


結語

Prototypeパターンとは、“一度設計されたものを、構造ごと再利用可能な形で複製する”ための設計戦略である。

  • 動的な構造生成におけるボイラープレート削減と構造の安定性を両立
  • 初期化の重いクラスや構成の複製を高速に行い、テンプレートとしての再利用性を最大化
  • Pythonにおいても copy.deepcopy() による柔軟な複製と、レジストリの導入による拡張性確保が容易

Pythonicとは、“構築よりも複製で整える”ことであり、
Prototypeパターンはその複製のデザインに美しさと効率を宿す構造である。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?