state design pattern java example
state design pattern java example
I'm happy to respond in English!
Design Patterns in Java: Observer Pattern Example
The Observer design pattern is a behavioral pattern that defines a one-to-many dependency between objects so that when one object changes its state, all its dependents are notified and updated automatically.
Problem Statement
Suppose you have an online shopping website where products are categorized into different departments (e.g., Electronics, Fashion, etc.). Each department has multiple product items. When the price of a specific product item is updated, it's essential to notify all relevant departments that offer this product so they can update their inventory prices accordingly.
Java Implementation
Here's an example implementation of the Observer pattern in Java:
// Product interface
public interface Product {
void setPrice(double newPrice);
}
// Concrete product: ElectronicsProduct
public class ElectronicsProduct implements Product {
private double price;
public void setPrice(double newPrice) {
price = newPrice;
System.out.println("Electronics product price updated to " + newPrice);
}
}
// Department interface
public interface Department {
void update(Product product);
}
// Concrete department: ElectronicsDepartment
public class ElectronicsDepartment implements Department {
@Override
public void update(Product product) {
System.out.println("Electronics department received an update about " + product.getClass().getSimpleName() + " price change.");
}
}
// Subject (ProductManager)
public class ProductManager {
private List observers;
public ProductManager() {
observers = new ArrayList<>();
}
public void registerObserver(Observer observer) {
observers.add(observer);
}
public void notifyObservers(Product product) {
for (Observer observer : observers) {
observer.update(product);
}
}
}
// Observer interface
public interface Observer {
void update(Product product);
}
// Concrete observer: ProductItemObserver
public class ProductItemObserver implements Observer {
@Override
public void update(Product product) {
System.out.println("Product item price changed to " + ((Product) product).getPrice());
}
}
Usage Example
Now let's create a scenario where we have an electronics product, and when its price is updated, it notifies all the registered departments:
public class Main {
public static void main(String[] args) {
// Create products and departments
Product electronicsProduct = new ElectronicsProduct();
Department electronicsDepartment = new ElectronicsDepartment();
// Register observer
ProductManager productManager = new ProductManager();
productManager.registerObserver(electronicsDepartment);
// Update price
electronicsProduct.setPrice(199.99);
// Output:
// Electronics department received an update about ElectronicsProduct price change.
}
}
Conclusion
In this example, we've demonstrated the Observer pattern in Java by creating a ProductManager
that maintains a list of observers (departments). When a product's price is updated, it notifies all registered departments, which can then react accordingly. This design pattern allows for loose coupling between objects, making it easier to manage complex relationships and scalability.
I hope this helps! Let me know if you have any further questions or need more examples.
What are the 4 states of thread in Java?
I'm happy to help!
In Java, a thread is a single flow of program execution that can run concurrently with other threads. There are four main states of a thread in Java:
Newborn State: This state refers to the creation of a new thread object. When you create a new Thread object, it enters the newborn state, where it doesn't have its own stack or native resources. At this point, the thread is not yet running. Runnable State: As soon as the thread's start() method is called, it transitions into the runnable state. In this state, the thread has a valid thread ID and can be scheduled to run by the operating system. The thread is still waiting for its turn to execute, but it's ready to go. Running State: When a thread enters the running state, it's executing code at runtime. This means the thread is consuming CPU resources, performing I/O operations, or waiting on some other resource. The running state is where most of the action happens! It's also worth noting that Java threads can be interrupted or paused while they're in this state. Dead State: Finally, when a thread has finished its execution or has been terminated (e.g., due to an exception), it enters the dead state. This state indicates that the thread is no longer alive and cannot be restarted or resumed. Dead threads are essentially garbage collected like any other Java object.Additional notes:
You can also consider another state, Waiting State, which occurs when a thread is waiting for some event or resource (e.g., waiting for a lock, I/O completion, or a condition variable). Some sources might group the states differently, such as considering the newborn state to be part of the runnable state. However, in general, the four main states (newborn, runnable, running, and dead) are widely recognized.Hope this helps! Let me know if you have any further questions