รูปแบบ Observer และ Strategy
นำ Observer มาใช้จัดการการพึ่งพา และใช้ Strategy สำหรับอัลกอริทึมที่สับเปลี่ยนแทนกันได้
รูปแบบ Observer และ Strategy เป็นบทเรียน Clean Architecture & Design Patterns in Practice ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clean Architecture & Design Patterns in Practice และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Behavioral Patterns: Actions & Interactions
Welcome to the world of Behavioral Design Patterns! These patterns focus on how objects interact and communicate, helping distribute responsibilities effectively.
They describe common communication patterns between objects, making your system more flexible and manageable.
Observer Pattern: Notifying Changes
First up is the Observer Pattern. Imagine you subscribe to a newsletter – when a new edition is out, you get notified! This pattern works similarly.
- It defines a one-to-many dependency between objects.
- When one object (the Subject) changes state, all its dependents (Observers) are notified and updated automatically.
It's great for event handling and distributed systems.
Observer Components: The Subject
The Subject (also known as Observable) is the object being watched. It has two main jobs:
- Maintain a list of its observers.
- Provide methods to attach (add) or detach (remove) observers.
- Notify all attached observers when its state changes.
Think of it as the news publisher.
Observer Components: The Observer
The Observer is any object that wants to be notified of changes in the Subject. It defines an update() method.
- When the Subject notifies, it calls each Observer's
update()method. - This method allows the Observer to react to the change, perhaps by fetching new data or updating its display.
These are your newsletter subscribers!
Observer Pattern: Publisher & Subscribers
Let's see the Observer pattern in action with a simple news publisher and readers. The NewsPublisher is our Subject, and NewsReaders are our Observers.
Try running the code to see how readers get updates!
import java.util.ArrayList;
import java.util.List;
// Observer Interface
interface Subscriber {
void update(String news);
}
// Subject Class
class NewsPublisher {
private List<Subscriber> subscribers = new ArrayList<>();
private String latestNews;
public void addSubscriber(Subscriber s) {
subscribers.add(s);
}
public void removeSubscriber(Subscriber s) {
subscribers.remove(s);
}
public void publishNews(String news) {
this.latestNews = news;
notifySubscribers();
}
private void notifySubscribers() {
for (Subscriber s : subscribers) {
s.update(latestNews);
}
}
}
// Concrete Observer
class NewsReader implements Subscriber {
private String name;
public NewsReader(String name) {
this.name = name;
}
@Override
public void update(String news) {
System.out.println(name + " received: " + news);
}
}
public class Main {
public static void main(String[] args) {
NewsPublisher publisher = new NewsPublisher();
NewsReader reader1 = new NewsReader("Alice");
NewsReader reader2 = new NewsReader("Bob");
publisher.addSubscriber(reader1);
publisher.addSubscriber(reader2);
publisher.publishNews("Breaking: New programming course released!");
System.out.println("\nAlice unsubscribes...");
publisher.removeSubscriber(reader1);
publisher.publishNews("Update: Course enrollment extended!");
}
}Strategy Pattern: Choosing Algorithms
Next, we have the Strategy Pattern. This pattern allows you to define a family of algorithms, encapsulate each one, and make them interchangeable.
It lets the algorithm vary independently from clients that use it. Think of choosing different payment methods (credit card, PayPal, bank transfer) at checkout.
Strategy Components: The Strategy
The Strategy is an interface or abstract class that declares a common operation for all supported algorithms.
- Each specific algorithm (e.g.,
CreditCardPayment,PayPalPayment) implements this interface. - This ensures they all have the same method signature, making them interchangeable.
Strategy Components: The Context
The Context is the class that holds a reference to a Strategy object. It defines an interface for clients to interact with.
- The Context does not know which concrete strategy it is using.
- It delegates the execution of the algorithm to its current Strategy object.
This keeps the Context simple and flexible, as it doesn't need to change when new strategies are added.
Strategy Pattern: Payment Methods
Here's a practical example of the Strategy pattern. We have different payment strategies (Credit Card, PayPal) and a ShoppingCart as our Context.
Notice how the ShoppingCart can easily switch between payment methods without changing its own core logic.
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String card) { this.cardNumber = card; }
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card " + cardNumber);
}
}
class PayPalPayment implements PaymentStrategy {
private String email;
public PayPalPayment(String email) { this.email = email; }
@Override
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal account: " + email);
}
}
class ShoppingCart {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void checkout(int amount) {
if (strategy == null) {
System.out.println("Please set a payment strategy first.");
return;
}
strategy.pay(amount);
}
}
public class Main {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
// Pay with Credit Card
cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
cart.checkout(100);
// Pay with PayPal
cart.setPaymentStrategy(new PayPalPayment("user@example.com"));
cart.checkout(50);
}
}Quick Check: Observer or Strategy?
Consider a stock trading application. It needs to calculate trading fees using different methods (e.g., a flat fee, a percentage of trade value, or a tiered system) based on the user's account type. The application should be able to easily switch between these methods.
Recap: Notifying & Swapping
Great job! You've explored two powerful behavioral design patterns:
- Observer Pattern: Manages one-to-many dependencies, where a Subject notifies multiple Observers of state changes. It promotes loose coupling between components.
- Strategy Pattern: Allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. It helps in swapping algorithms at runtime, promoting flexibility and clean code.
These patterns help make your code more modular, flexible, and easier to maintain!
คำถามที่พบบ่อย
บทเรียน “รูปแบบ Observer และ Strategy” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “รูปแบบ Observer และ Strategy” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clean Architecture & Design Patterns in Practice ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “รูปแบบ Observer และ Strategy”
นำ Observer มาใช้จัดการการพึ่งพา และใช้ Strategy สำหรับอัลกอริทึมที่สับเปลี่ยนแทนกันได้ คุณปฏิบัติ Clean Architecture & Design Patterns in Practice ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clean Architecture & Design Patterns in Practice หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clean Architecture & Design Patterns in Practice บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “รูปแบบ Observer และ Strategy” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clean Architecture & Design Patterns in Practice นี้ได้ไหม
ได้ บทเรียน Clean Architecture & Design Patterns in Practice ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- รูปแบบ Observer และ Strategy
- รูปแบบ Command และ Iterator
- รูปแบบ Template Method และ State
- Mediator และ Chain of Responsibility