Welcome to CodeYourCraft's Java Tutorial on Behavioral Patterns! In this lesson, we'll dive into a fascinating world where objects communicate and collaborate, making our code more modular, flexible, and easier to maintain. 💡
Behavioral patterns are design patterns that identify common communication patterns between objects and realize these communication patterns. They help us design flexible and scalable applications by promoting loose coupling and code reusability.
Observer Pattern 🎯
Strategy Pattern 🎯
Command Pattern 🎯
Template Method Pattern 🎯
We'll provide you with two complete, working examples of Strategy and Observer patterns to help you grasp these patterns better.
// Strategy Interface
interface ShippingStrategy {
double calculateShippingCost(double weight, String zone);
}
// Concrete Strategy Implementations
class WeightBasedShipping implements ShippingStrategy {
@Override
public double calculateShippingCost(double weight, String zone) {
double cost = weight * 10; // For simplicity, let's say cost is 10 times the weight
return cost;
}
}
class ZoneBasedShipping implements ShippingStrategy {
@Override
public double calculateShippingCost(double weight, String zone) {
double cost = 5.0;
if (zone.equals("zone1")) {
cost += weight * 2.0;
} else if (zone.equals("zone2")) {
cost += weight * 3.0;
} else {
cost += weight * 4.0;
}
return cost;
}
}
// Context Class
class ShoppingCart {
private ShippingStrategy strategy;
public void setShippingStrategy(ShippingStrategy strategy) {
this.strategy = strategy;
}
public double calculateTotalCost(double weight, String zone) {
double cost = strategy.calculateShippingCost(weight, zone);
// Add item costs, taxes, and other charges here
return cost;
}
}// Subject Interface
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// Concrete Subject Implementation
class StockQuote implements Subject {
private String symbol;
private double price;
private List<Observer> observers = new ArrayList<>();
public StockQuote(String symbol) {
this.symbol = symbol;
}
public void setPrice(double price) {
this.price = price;
notifyObservers();
}
public void registerObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(symbol, price);
}
}
}
// Observer Interface
interface Observer {
void update(String symbol, double price);
}
// Concrete Observer Implementations
class StockBroker implements Observer {
private String name;
public StockBroker(String name) {
this.name = name;
}
@Override
public void update(String symbol, double price) {
System.out.println(name + " received an update for " + symbol + " at $" + price);
}
}What is the Strategy pattern used for in Java?
What is the Observer pattern used for in Java?