Lập trình Hướng đối tượng Nâng cao với Python
Jake Roach
Data Engineer
class Student:
# Logic điều kiện với hành vi tương tự cho mọi nhánh
def explore_topic(self, resource_type, topic):
if resource_type == "Textbook":
print(f"Tham chiếu {topic} bằng sách giáo khoa")
self.reference_textbook(topic)
elif resource_type == "Blog":
print(f"Hãy xác thực thông tin trong blog!")
self.reference_blog(topic)
elif resource_type == "Video":
self.reference_video(topic)
Mẫu thiết kế dùng factory method để tạo đối tượng cho phương thức khác sử dụng
_ để ký hiệu factory method$$
Trước hết, hãy xem sản phẩm và sản phẩm cụ thể!
...
def _get_resource(self, resource_type):
if resource_type == "Textbook":
# Textbook, Blog và Video đều là
# resource
return Textbook()
elif resource_type == "Blog":
return Blog()
elif resource_type == "Video":
return Video()
class Resource(ABC):
@abstractmethod
def reference(self, topic):
pass
class Textbook(Resource):
def __init__(self):
self.index = {"Object-oriented Programming": ["Inheritance", ...]}
def reference(self, topic):
print(f"Tham chiếu {topic} bằng sách giáo khoa")
return self.index.get(topic)
# Tương tự cho Blog, Video
class Student:
def explore_topic(self, resource_type, topic):
if resource_type == "Textbook":
texbook = Textbook() # Tạo instance của lớp triển khai Resource
texbook.reference(topic) # Gọi phương thức reference()
elif resource_type == "Blog":
blog = Blog()
blog.reference(topic)
elif resource_type == "Video":
video = Video()
video.reference(topic)
class Student:
# Factory method để trả về Resource
def _get_resource(self, resource_type):
if resource_type == "Textbook":
return Textbook()
elif resource_type == "Blog":
return Blog()
elif resource_type == "Video":
return Video()
def explore_topic(self, resource_type, topic):
resource = self._get_resource(resource_type) # Lấy resource
return resource.reference(topic)
# Tạo đối tượng Student, rồi tham chiếu một textbook
lester = Student()
lester.explore_topic("Textbook", "Object-oriented Programming")
# Dễ dàng chuyển sang resource khác
lester.explore_topic("Video", "Object-oriented Programming")
Tham chiếu Object-oriented Programming bằng sách giáo khoa
["Inheritance", "Constructors", "Class-level methods"]
Video hữu ích cho người học trực quan hoặc thính giác
["Classes", "Methods", "Attributes", "self"]
Lập trình Hướng đối tượng Nâng cao với Python