策略模式 (Strategy Pattern):
java.util.Comparator
以下是一个简单的Java策略模式的例子,涉及一个商品的价格计算场景。我们将定义一个PriceCalculator
类,它使用不同的价格计算策略来计算商品的最终价格。
import java.util.HashMap;
import java.util.Map;
// 策略接口
interface PricingStrategy {
double calculatePrice(double originalPrice);
}
// 具体策略1:打折策略
class DiscountPricingStrategy implements PricingStrategy {
private double discountRate;
public DiscountPricingStrategy(double discountRate) {
this.discountRate = discountRate;
}
@Override
public double calculatePrice(double originalPrice) {
return originalPrice * (1 - discountRate);
}
}
// 具体策略2:满减策略
class FullReductionPricingStrategy implements PricingStrategy {
private double threshold;
private double reductionAmount;
public FullReductionPricingStrategy(double threshold, double reductionAmount) {
this.threshold = threshold;
this.reductionAmount = reductionAmount;
}
@Override
public double calculatePrice(double originalPrice) {
return originalPrice >= threshold ? originalPrice - reductionAmount : originalPrice;
}
}
// 上下文类,用于设置和执行策略
class PriceCalculator {
private PricingStrategy pricingStrategy;
public void setPricingStrategy(PricingStrategy pricingStrategy) {
this.pricingStrategy = pricingStrategy;
}
public double calculateFinalPrice(double originalPrice) {
if (pricingStrategy == null) {
throw new IllegalStateException("Pricing strategy not set");
}
return pricingStrategy.calculatePrice(originalPrice);
}
}
public class StrategyPatternExample {
public static void main(String[] args) {
// 创建商品价格计算器
PriceCalculator priceCalculator = new PriceCalculator();
// 商品原始价格
double originalPrice = 100.0;
// 使用打折策略
PricingStrategy discountStrategy = new DiscountPricingStrategy(0.2);
priceCalculator.setPricingStrategy(discountStrategy);
double discountedPrice = priceCalculator.calculateFinalPrice(originalPrice);
System.out.println("Discounted Price: " + discountedPrice);
// 使用满减策略
PricingStrategy fullReductionStrategy = new FullReductionPricingStrategy(80.0, 10.0);
priceCalculator.setPricingStrategy(fullReductionStrategy);
double reducedPrice = priceCalculator.calculateFinalPrice(originalPrice);
System.out.println("Reduced Price: " + reducedPrice);
}
}
这个例子中,PricingStrategy
是一个策略接口,具体的打折策略和满减策略分别实现了这个接口。PriceCalculator
是上下文类,用于设置和执行不同的策略。在main
方法中,我们创建了一个商品价格计算器,分别使用了打折策略和满减策略来计算最终价格。你可以运行这个例子,看到不同策略下的最终价格计算结果。
java.util.Observer
和 java.util.Observable
当涉及观察者模式时,通常会有一个主题对象(Subject),它会维护一个观察者(Observer)列表,并通知这些观察者当其状态发生改变。下面是一个简单的 Java 观察者模式示例,模拟了一个简单的新闻发布系统。
import java.util.ArrayList;
import java.util.List;
// 主题接口
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers(String news);
}
// 具体主题类
class NewsPublisher implements Subject {
private List observers;
private String latestNews;
public NewsPublisher() {
this.observers = new ArrayList<>();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers(String news) {
for (Observer observer : observers) {
observer.update(news);
}
}
// 模拟新闻发布
public void publishNews(String news) {
this.latestNews = news;
notifyObservers(news);
}
}
// 观察者接口
interface Observer {
void update(String news);
}
// 具体观察者类
class NewsSubscriber implements Observer {
private String subscriberName;
public NewsSubscriber(String subscriberName) {
this.subscriberName = subscriberName;
}
@Override
public void update(String news) {
System.out.println(subscriberName + " received news: " + news);
}
}
public class ObserverPatternExample {
public static void main(String[] args) {
// 创建新闻发布者
NewsPublisher publisher = new NewsPublisher();
// 创建订阅者
Observer subscriber1 = new NewsSubscriber("Subscriber 1");
Observer subscriber2 = new NewsSubscriber("Subscriber 2");
// 订阅新闻
publisher.registerObserver(subscriber1);
publisher.registerObserver(subscriber2);
// 发布新闻
publisher.publishNews("Breaking News: Observers pattern example!");
// 移除一个订阅者
publisher.removeObserver(subscriber2);
// 再次发布新闻
publisher.publishNews("Second Edition: More updates!");
}
}
这个示例中,NewsPublisher
是主题类,负责管理观察者列表并通知它们有关最新新闻的更新。NewsSubscriber
是具体的观察者类,实现了 Observer
接口。在 main
方法中,创建了一个新闻发布者,并添加了两个订阅者。当发布者发布新闻时,所有订阅者都会收到相应的新闻更新。可以运行这个示例来查看观察者模式的效果。
java.util.Collections#sort()
模板方法模式通常涉及一个抽象类定义了一个算法的骨架,将一些步骤延迟到子类中。以下是一个简单的 Java 模板方法模式的例子,模拟了一种饮料制作的过程。
// 模板方法抽象类
abstract class BeverageTemplate {
// 模板方法,定义了饮料制作的步骤
public final void makeBeverage() {
boilWater();
brew();
pourInCup();
addCondiments();
System.out.println("Beverage is ready!");
}
// 具体步骤1:烧水
private void boilWater() {
System.out.println("Boiling water");
}
// 具体步骤2:冲泡
protected abstract void brew();
// 具体步骤3:倒入杯中
private void pourInCup() {
System.out.println("Pouring into cup");
}
// 具体步骤4:加调料
protected abstract void addCondiments();
}
// 具体类1:制作咖啡
class Coffee extends BeverageTemplate {
@Override
protected void brew() {
System.out.println("Brewing coffee grounds");
}
@Override
protected void addCondiments() {
System.out.println("Adding sugar and milk");
}
}
// 具体类2:制作茶
class Tea extends BeverageTemplate {
@Override
protected void brew() {
System.out.println("Steeping the tea");
}
@Override
protected void addCondiments() {
System.out.println("Adding lemon");
}
}
public class TemplateMethodPatternExample {
public static void main(String[] args) {
// 制作咖啡
BeverageTemplate coffee = new Coffee();
System.out.println("Making coffee...");
coffee.makeBeverage();
System.out.println();
// 制作茶
BeverageTemplate tea = new Tea();
System.out.println("Making tea...");
tea.makeBeverage();
}
}
在这个例子中,BeverageTemplate
是模板方法抽象类,它定义了一个 makeBeverage
模板方法,其中包含了制作饮料的通用步骤,如烧水、冲泡、倒入杯中和加调料。Coffee
和 Tea
是具体的子类,分别实现了 brew
和 addCondiments
方法以定制制作咖啡和茶的具体步骤。
在 main
方法中,创建了一个咖啡对象和一个茶对象,并分别调用它们的 makeBeverage
方法。你可以运行这个示例来查看模板方法模式的实际应用。