
7 Design Patterns Mà Mọi Developer Nên Biết
Table of Contents
Table of Contents
7 Design Patterns Mà Mọi Developer Nên Biết
Design patterns là các mẫu thiết kế phần mềm đã được kiểm chứng, giúp giải quyết những vấn đề lặp lại trong lập trình. Áp dụng đúng design pattern giúp code dễ bảo trì, mở rộng và tối ưu hiệu suất. Bài viết này tổng hợp 7 mẫu thiết kế phổ biến nhất mà mọi lập trình viên nên biết, kèm ví dụ minh họa và ứng dụng thực tế.
1. Singleton Pattern
Singleton đảm bảo chỉ có một instance duy nhất của một class trong suốt vòng đời ứng dụng, thường dùng cho logging, kết nối database.
- Ưu điểm: Quản lý trạng thái toàn cục, tiết kiệm tài nguyên.
- Nhược điểm: Khó test, cần chú ý thread-safe.
Ví dụ:
class Singleton:
static instance = null
static method get_instance():
if instance == null then
instance = new Singleton()
end if
return instance
end method
# Sử dụng Singleton
singleton = Singleton.get_instance()
2. Builder Pattern
Builder giúp tạo object phức tạp bằng cách chia nhỏ quá trình khởi tạo thành nhiều bước, phù hợp với class có nhiều tham số tùy chọn.
Ví dụ:
class ProductBuilder:
method __init__():
this.product = new Product()
end method
method set_name(name):
this.product.name = name
return this
end method
method set_price(price):
this.product.price = price
return this
end method
method build():
return this.product
end method
# Sử dụng Builder
builder = new ProductBuilder()
product = builder.set_name("Laptop").set_price(1500).build()
3. Factory Pattern
Factory cung cấp interface tạo object mà không cần biết class cụ thể, giúp code linh hoạt và dễ mở rộng.
Ví dụ:
class UserFactory:
static method create_user(user_type):
if user_type == "admin" then
return new Admin()
else if user_type == "moderator" then
return new Moderator()
else
return new RegularUser()
end if
end method
# Sử dụng Factory
user = UserFactory.create_user("admin")
4. Facade Pattern
Facade ẩn đi sự phức tạp của hệ thống, cung cấp interface đơn giản cho client, thường dùng trong API hoặc UI.
Ví dụ:
class ComplexSystem:
method operation_a():
print("Operation A")
end method
method operation_b():
print("Operation B")
end method
class Facade:
method __init__():
this.system = new ComplexSystem()
end method
method simplified_operation():
this.system.operation_a()
this.system.operation_b()
end method
# Sử dụng Facade
facade = new Facade()
facade.simplified_operation()
5. Adapter Pattern
Adapter giúp kết nối hai interface không tương thích, thường dùng khi tích hợp API hoặc thư viện bên ngoài.
Ví dụ:
class OldSystem:
method old_method():
print("Old Method")
end method
class Adapter:
method __init__(old_system):
this.old_system = old_system
end method
method new_method():
this.old_system.old_method()
end method
# Sử dụng Adapter
old_system = new OldSystem()
adapter = new Adapter(old_system)
adapter.new_method()
6. Strategy Pattern
Strategy cho phép thay đổi thuật toán thực thi tại runtime, giúp code tuân thủ nguyên tắc Open-Closed.
Ví dụ:
class TravelStrategy:
method travel():
pass
end method
class CarStrategy(TravelStrategy):
method travel():
print("Travel by Car")
end method
class BikeStrategy(TravelStrategy):
method travel():
print("Travel by Bike")
end method
class Context:
method __init__(strategy):
this.strategy = strategy
end method
method execute_strategy():
this.strategy.travel()
end method
# Sử dụng Strategy
context = new Context(new CarStrategy())
context.execute_strategy()
7. Observer Pattern
Observer giúp theo dõi và phản ứng với sự thay đổi trạng thái, thường dùng cho notification, event system.
Ví dụ:
class Subject:
method __init__():
this.observers = []
end method
method attach(observer):
this.observers.append(observer)
end method
method notify():
for observer in this.observers do
observer.update()
end for
end method
class Observer:
method update():
pass
end method
class ConcreteObserver(Observer):
method update():
print("Observer Updated")
end method
# Sử dụng Observer
subject = new Subject()
observer = new ConcreteObserver()
subject.attach(observer)
subject.notify()
Tại sao nên học Design Patterns?
- Tăng khả năng giải quyết vấn đề, tối ưu code.
- Dễ dàng trao đổi, làm việc nhóm nhờ ngôn ngữ chung.
- Nâng cao kỹ năng thiết kế hệ thống, chuẩn bị cho phỏng vấn.
Tài liệu tham khảo:
- Refactoring Guru - Design Patterns
- Wikipedia - Software design pattern
- Sách “Head First Design Patterns”
Hãy thực hành và áp dụng các pattern này vào dự án thực tế để hiểu sâu hơn!
Related Posts
7 Design Patterns Mà Mọi Developer Nên Biết
Khám phá 7 design patterns phổ biến nhất trong phát triển phần mềm: Singleton, Builder, Factory, Facade, Adapter, Strategy, Observer. Bài viết giải thích chi tiết, ví dụ minh họa, ứng dụng thực tế giúp developer nâng cao kỹ năng thiết kế hệ thống.
Read more7 Design Patterns Every Developer Should Know
Explore 7 essential design patterns: Singleton, Builder, Factory, Facade, Adapter, Strategy, and Observer with examples and real-world applications.
Read moreKiến Trúc Backend for Frontend (BFF): Hiểu Rõ và Ứng Dụng Hiệu Quả
Khám phá kiến trúc Backend for Frontend (BFF), lợi ích, thách thức, ví dụ thực tế và thực tiễn tốt nhất khi áp dụng BFF vào dự án.
Read more