Python

# -
class Car:
    def __init__(self, brand, model, color, engine_type):
        self.brand = brand
        self.model = model
        self.color = color
        self.engine_type = engine_type
        #
        self.initialize_complex_components()
   
    def initialize_complex_components(self):
        #
        import time
        time.sleep(1)  # 1
        print(f" {self.brand} {self.model} ...")

#
car1 = Car("Toyota", "Camry", "", "2.5L")
car2 = Car("Toyota", "Camry", "", "2.5L")  #


Python copy

python-prototype.png [python-prototype.png]

Python

Python

copy.copy()
copy.deepcopy()

import copy
from abc import ABC, abstractmethod
from typing import Any

class Prototype(ABC):
    """"""
   
    @abstractmethod
    def clone(self) -> Any:
        """ - """
        pass

class CarPrototype(Prototype):
    """"""
   
    def __init__(self, brand: str, model: str, color: str, engine_type: str):
        self.brand = brand
        self.model = model
        self.color = color
        self.engine_type = engine_type
        self.accessories = []  #
        self.initialize_complex_components()
   
    def initialize_complex_components(self):
        """"""
        print(f" {self.brand} {self.model} ...")
        #
   
    def add_accessory(self, accessory: str):
        """"""
        self.accessories.append(accessory)
   
    def clone(self) -> 'CarPrototype':
        """ - """
        return copy.deepcopy(self)
   
    def display_info(self):
        """"""
        info = f"{self.brand} {self.model} - : {self.color}, : {self.engine_type}"
        if self.accessories:
            info += f", : {', '.join(self.accessories)}"
        print(info)

#
print("=== ===")
original_car = CarPrototype("Toyota", "Camry", "", "2.5L")
original_car.add_accessory("")
original_car.add_accessory("")
original_car.display_info()

print("\n=== ===")
#
car1 = original_car.clone()
car1.color = ""  #
car1.display_info()

car2 = original_car.clone()
car2.color = ""
car2.add_accessory("")  #
car2.display_info()

#
print("\n=== ===")
original_car.display_info()

===  ===
 Toyota Camry ...
Toyota Camry - : , : 2.5L, : , 

===  ===
Toyota Camry - : , : 2.5L, : , 
Toyota Camry - : , : 2.5L, : , , 

===  ===
Toyota Camry - : , : 2.5L, : , 

1

class GameCharacter(Prototype):
    """"""
   
    def __init__(self, name: str, character_class: str, level: int = 1):
        self.name = name
        self.character_class = character_class
        self.level = level
        self.skills = []
        self.equipment = {}
        self.initialize_character()
   
    def initialize_character(self):
        """ - """
        print(f" {self.name} ...")
        #
        base_skills = {
            "Warrior": ["", "", ""],
            "Mage": ["", "", ""],
            "Archer": ["", "", ""]
        }
        self.skills = base_skills.get(self.character_class, [])
   
    def add_skill(self, skill: str):
        """"""
        self.skills.append(skill)
   
    def equip_item(self, slot: str, item: str):
        """"""
        self.equipment[slot] = item
   
    def clone(self) -> 'GameCharacter':
        """"""
        return copy.deepcopy(self)
   
    def show_status(self):
        """"""
        print(f": {self.name} ({self.character_class}) - : {self.level}")
        print(f": {', '.join(self.skills)}")
        if self.equipment:
            equipment_str = ', '.join([f"{k}: {v}" for k, v in self.equipment.items()])
            print(f": {equipment_str}")

#
print("=== ===")
warrior_template = GameCharacter("", "Warrior")
warrior_template.equip_item("", "")
warrior_template.equip_item("", "")
warrior_template.show_status()

print("\n=== ===")
player1 = warrior_template.clone()
player1.name = ""
player1.level = 5
player1.add_skill("")
player1.show_status()

player2 = warrior_template.clone()
player2.name = ""
player2.level = 3
player2.equip_item("", "")
player2.show_status()

2

class DocumentTemplate(Prototype):
    """"""
   
    def __init__(self, template_name: str):
        self.template_name = template_name
        self.headers = {}
        self.content_sections = []
        self.styles = {}
        self.load_template_config()
   
    def load_template_config(self):
        """ - """
        print(f" {self.template_name} ...")
        #
        self.headers = {
            "title": f"{self.template_name} ",
            "author": "",
            "date": "2024-01-01"
        }
        self.styles = {
            "font_family": "Arial",
            "font_size": "12pt",
            "line_spacing": "1.5"
        }
   
    def clone(self) -> 'DocumentTemplate':
        """"""
        return copy.deepcopy(self)
   
    def customize(self, title: str = None, author: str = None):
        """"""
        if title:
            self.headers["title"] = title
        if author:
            self.headers["author"] = author
        self.headers["date"] = "2024-12-19"  #
   
    def add_section(self, section_title: str, content: str):
        """"""
        self.content_sections.append({
            "title": section_title,
            "content": content
        })
   
    def render(self):
        """"""
        print(f"\n=== {self.headers['title']} ===")
        print(f": {self.headers['author']}")
        print(f": {self.headers['date']}")
        print(f": {self.styles}")
        for section in self.content_sections:
            print(f"\n## {section['title']}")
            print(section['content'])
        print("=" * 50)

#
print("=== ===")
report_template = DocumentTemplate("")
report_template.add_section("", "")
report_template.render()

print("\n=== ===")
monthly_report = report_template.clone()
monthly_report.customize("", "")
monthly_report.add_section("", "100")
monthly_report.render()

project_report = report_template.clone()
project_report.customize("", "")
project_report.add_section("", "")
project_report.render()


1.

class SmartPrototype(Prototype):
    def __init__(self, data):
        self.data = data
        self.reference_data = []  #
   
    def clone(self):
        """"""
        new_obj = copy.copy(self)  #
        new_obj.reference_data = self.reference_data  #
        new_obj.data = copy.deepcopy(self.data)  #
        return new_obj

2.

class Node(Prototype):
    def __init__(self, value):
        self.value = value
        self.children = []
   
    def add_child(self, child):
        self.children.append(child)
   
    def clone(self):
        """"""
        #
        return copy.deepcopy(self)

3.

class PrototypeRegistry:
    """ - """
   
    def __init__(self):
        self._prototypes = {}
   
    def register_prototype(self, name: str, prototype: Prototype):
        """"""
        self._prototypes[name] = prototype
   
    def unregister_prototype(self, name: str):
        """"""
        if name in self._prototypes:
            del self._prototypes[name]
   
    def clone_prototype(self, name: str) -> Prototype:
        """"""
        if name not in self._prototypes:
            raise ValueError(f" {name} ")
        return self._prototypes[name].clone()
   
    def list_prototypes(self):
        """"""
        return list(self._prototypes.keys())

#
registry = PrototypeRegistry()
registry.register_prototype("basic_car", CarPrototype("Toyota", "Camry", "", "2.5L"))
registry.register_prototype("warrior", GameCharacter("", "Warrior"))

#
new_car = registry.clone_prototype("basic_car")
new_warrior = registry.clone_prototype("warrior")

1

CarPrototype

  • (VIN)

2

3


Python

  • copy