banner
Jun 11, 2023
113 Views

Prototype Pattern

Written by
banner

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

Mô tả loại đối tượng cần tạo bằng một phiên bản nguyên mẫu và tạo ra các đối tượng mới bằng cách sao chép nguyên mẫu này.

import copy

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

class Novel(Book):
    def __init__(self, name):
        self.name = name

    def say_hello(self):
        print(f"Hello, I'm {self.name}")

# Create a prototype object
prototype = Novel("Harry Potter")

# Clone the prototype object
clone1 = prototype.clone()
clone1.say_hello()  # Output: Hello, I'm Harry Potter

# Clone the prototype object again
clone2 = prototype.clone()
clone2.say_hello()  # Output: Hello, I'm Harry Potter
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *