from __future__ import annotations
from abc import ABC,abstractmethod
classCreator(ABC):
"""
Lớp Creator khai báo phương thức factory method mà sẽ trả về một đối tượng của
lớp Product. Các lớp con của Creator sẽ cung cấp hiện thực cho phương thức này.
"""
@abstractmethod
def factory_method(self):
"""
Lưu ý Creator cũng có thể tạo một hiện thực mặc định cho phương thức factory.
"""
pass
def some_operation(self)-> str:
"""
Cũng lưu ý rằng, mặc dù tên của nó, nhưng trách nhiệm chỉnh của Creator không phải là
tạo product. Thông thường, nó chứa những logic cốt lõi dựa trên đối tượng Product,
được trả về bởi phương thức factory. Các lớp con có thể thay đổi logic này không
trực tiếp bằng cách ghi đè phương thức factory và trả về một kiểu khác của product.
"""
# Gọi phương thức factory để tạo một đối tượng Product.
product =self.factory_method()
# Giờ thì sử dụng product.
result=f"Creator: The same creator's code has just worked with {product.operation()}"
return result
"""
Concrete Creator ghi đè phương thức factory để thay đổi kiểu trả về của product.
"""
classConcreteCreator1(Creator):
"""
Lưu ý rằng chữ ký của phương thức vẫn sử dụng kiểu trừu tượng, mặc dù kiểu
product cụ thể thực sự được trả về từ phương thức. Bằng cách này, Creator có
thể độc lập với các lớp product cụ thể.
"""
def factory_method(self)-> ConcreteProduct1:
returnConcreteProduct1()
classConcreteCreator2(Creator):
def factory_method(self)-> ConcreteProduct2:
returnConcreteProduct2()
classProduct(ABC):
"""
Interface Product khai báo các phương thức mà tất cả các concrete product phải hiện thực.
"""
@abstractmethod
def operation(self)->str:
pass
"""
Concrete Product cung cấp các hiện thực khác nhau của interface Product.
"""
classConcreteProduct1(Product):
def operation(self)->str:
return "{Result of the ConcreteProduct1}"
classConcreteProduct2(Product):
def operation(self)->str:
return"{Result of the ConcreteProduct2}"
def client_code(creator:Creator)->None:
"""
Mã client làm việc với một thể hiện của concrete creator, mặc dù thông qua interface
cơ sở của nó. Miễn là client còn tiếp tục làm việc với creator thông qua interface
cơ sở, bạn có thể truyền nó vào bất kỳ lớp con nào của creator.
"""
print(f"Client: I'm not aware of the creator's class, but it still works.\n"
f"{creator.some_operation()}", end="")
if__name__=="__main__":
print("App: Launched with the ConcreteCreator1.")
client_code(ConcreteCreator1())
print("\n")
print("App: Launched with the ConcreteCreator2.")
client_code(ConcreteCreator2())