• 设计模式例子


    策略模式(Strategy Pattern)

    1. 策略模式 (Strategy Pattern):

      • 定义一系列算法,将每个算法都封装起来,并使它们之间可以互换。
      • 例如:java.util.Comparator

    以下是一个简单的Java策略模式的例子,涉及一个商品的价格计算场景。我们将定义一个PriceCalculator类,它使用不同的价格计算策略来计算商品的最终价格。

    1. import java.util.HashMap;
    2. import java.util.Map;
    3. // 策略接口
    4. interface PricingStrategy {
    5. double calculatePrice(double originalPrice);
    6. }
    7. // 具体策略1:打折策略
    8. class DiscountPricingStrategy implements PricingStrategy {
    9. private double discountRate;
    10. public DiscountPricingStrategy(double discountRate) {
    11. this.discountRate = discountRate;
    12. }
    13. @Override
    14. public double calculatePrice(double originalPrice) {
    15. return originalPrice * (1 - discountRate);
    16. }
    17. }
    18. // 具体策略2:满减策略
    19. class FullReductionPricingStrategy implements PricingStrategy {
    20. private double threshold;
    21. private double reductionAmount;
    22. public FullReductionPricingStrategy(double threshold, double reductionAmount) {
    23. this.threshold = threshold;
    24. this.reductionAmount = reductionAmount;
    25. }
    26. @Override
    27. public double calculatePrice(double originalPrice) {
    28. return originalPrice >= threshold ? originalPrice - reductionAmount : originalPrice;
    29. }
    30. }
    31. // 上下文类,用于设置和执行策略
    32. class PriceCalculator {
    33. private PricingStrategy pricingStrategy;
    34. public void setPricingStrategy(PricingStrategy pricingStrategy) {
    35. this.pricingStrategy = pricingStrategy;
    36. }
    37. public double calculateFinalPrice(double originalPrice) {
    38. if (pricingStrategy == null) {
    39. throw new IllegalStateException("Pricing strategy not set");
    40. }
    41. return pricingStrategy.calculatePrice(originalPrice);
    42. }
    43. }
    44. public class StrategyPatternExample {
    45. public static void main(String[] args) {
    46. // 创建商品价格计算器
    47. PriceCalculator priceCalculator = new PriceCalculator();
    48. // 商品原始价格
    49. double originalPrice = 100.0;
    50. // 使用打折策略
    51. PricingStrategy discountStrategy = new DiscountPricingStrategy(0.2);
    52. priceCalculator.setPricingStrategy(discountStrategy);
    53. double discountedPrice = priceCalculator.calculateFinalPrice(originalPrice);
    54. System.out.println("Discounted Price: " + discountedPrice);
    55. // 使用满减策略
    56. PricingStrategy fullReductionStrategy = new FullReductionPricingStrategy(80.0, 10.0);
    57. priceCalculator.setPricingStrategy(fullReductionStrategy);
    58. double reducedPrice = priceCalculator.calculateFinalPrice(originalPrice);
    59. System.out.println("Reduced Price: " + reducedPrice);
    60. }
    61. }

    这个例子中,PricingStrategy是一个策略接口,具体的打折策略和满减策略分别实现了这个接口。PriceCalculator是上下文类,用于设置和执行不同的策略。在main方法中,我们创建了一个商品价格计算器,分别使用了打折策略和满减策略来计算最终价格。你可以运行这个例子,看到不同策略下的最终价格计算结果。

    观察者模式(Observer Pattern)

    • 定义了一种一对多的依赖关系,使得当一个对象改变状态时,所有依赖于它的对象都会得到通知并自动更新。
    • 例如:java.util.Observer 和 java.util.Observable

    当涉及观察者模式时,通常会有一个主题对象(Subject),它会维护一个观察者(Observer)列表,并通知这些观察者当其状态发生改变。下面是一个简单的 Java 观察者模式示例,模拟了一个简单的新闻发布系统。

    1. import java.util.ArrayList;
    2. import java.util.List;
    3. // 主题接口
    4. interface Subject {
    5. void registerObserver(Observer observer);
    6. void removeObserver(Observer observer);
    7. void notifyObservers(String news);
    8. }
    9. // 具体主题类
    10. class NewsPublisher implements Subject {
    11. private List observers;
    12. private String latestNews;
    13. public NewsPublisher() {
    14. this.observers = new ArrayList<>();
    15. }
    16. @Override
    17. public void registerObserver(Observer observer) {
    18. observers.add(observer);
    19. }
    20. @Override
    21. public void removeObserver(Observer observer) {
    22. observers.remove(observer);
    23. }
    24. @Override
    25. public void notifyObservers(String news) {
    26. for (Observer observer : observers) {
    27. observer.update(news);
    28. }
    29. }
    30. // 模拟新闻发布
    31. public void publishNews(String news) {
    32. this.latestNews = news;
    33. notifyObservers(news);
    34. }
    35. }
    36. // 观察者接口
    37. interface Observer {
    38. void update(String news);
    39. }
    40. // 具体观察者类
    41. class NewsSubscriber implements Observer {
    42. private String subscriberName;
    43. public NewsSubscriber(String subscriberName) {
    44. this.subscriberName = subscriberName;
    45. }
    46. @Override
    47. public void update(String news) {
    48. System.out.println(subscriberName + " received news: " + news);
    49. }
    50. }
    51. public class ObserverPatternExample {
    52. public static void main(String[] args) {
    53. // 创建新闻发布者
    54. NewsPublisher publisher = new NewsPublisher();
    55. // 创建订阅者
    56. Observer subscriber1 = new NewsSubscriber("Subscriber 1");
    57. Observer subscriber2 = new NewsSubscriber("Subscriber 2");
    58. // 订阅新闻
    59. publisher.registerObserver(subscriber1);
    60. publisher.registerObserver(subscriber2);
    61. // 发布新闻
    62. publisher.publishNews("Breaking News: Observers pattern example!");
    63. // 移除一个订阅者
    64. publisher.removeObserver(subscriber2);
    65. // 再次发布新闻
    66. publisher.publishNews("Second Edition: More updates!");
    67. }
    68. }

    这个示例中,NewsPublisher 是主题类,负责管理观察者列表并通知它们有关最新新闻的更新。NewsSubscriber 是具体的观察者类,实现了 Observer 接口。在 main 方法中,创建了一个新闻发布者,并添加了两个订阅者。当发布者发布新闻时,所有订阅者都会收到相应的新闻更新。可以运行这个示例来查看观察者模式的效果。

    模板方法模式(Template Method Pattern)

    • 定义一个算法的骨架,将一些步骤延迟到子类中。
    • 例如:java.util.Collections#sort()

    模板方法模式通常涉及一个抽象类定义了一个算法的骨架,将一些步骤延迟到子类中。以下是一个简单的 Java 模板方法模式的例子,模拟了一种饮料制作的过程。

    1. // 模板方法抽象类
    2. abstract class BeverageTemplate {
    3. // 模板方法,定义了饮料制作的步骤
    4. public final void makeBeverage() {
    5. boilWater();
    6. brew();
    7. pourInCup();
    8. addCondiments();
    9. System.out.println("Beverage is ready!");
    10. }
    11. // 具体步骤1:烧水
    12. private void boilWater() {
    13. System.out.println("Boiling water");
    14. }
    15. // 具体步骤2:冲泡
    16. protected abstract void brew();
    17. // 具体步骤3:倒入杯中
    18. private void pourInCup() {
    19. System.out.println("Pouring into cup");
    20. }
    21. // 具体步骤4:加调料
    22. protected abstract void addCondiments();
    23. }
    24. // 具体类1:制作咖啡
    25. class Coffee extends BeverageTemplate {
    26. @Override
    27. protected void brew() {
    28. System.out.println("Brewing coffee grounds");
    29. }
    30. @Override
    31. protected void addCondiments() {
    32. System.out.println("Adding sugar and milk");
    33. }
    34. }
    35. // 具体类2:制作茶
    36. class Tea extends BeverageTemplate {
    37. @Override
    38. protected void brew() {
    39. System.out.println("Steeping the tea");
    40. }
    41. @Override
    42. protected void addCondiments() {
    43. System.out.println("Adding lemon");
    44. }
    45. }
    46. public class TemplateMethodPatternExample {
    47. public static void main(String[] args) {
    48. // 制作咖啡
    49. BeverageTemplate coffee = new Coffee();
    50. System.out.println("Making coffee...");
    51. coffee.makeBeverage();
    52. System.out.println();
    53. // 制作茶
    54. BeverageTemplate tea = new Tea();
    55. System.out.println("Making tea...");
    56. tea.makeBeverage();
    57. }
    58. }

    在这个例子中,BeverageTemplate 是模板方法抽象类,它定义了一个 makeBeverage 模板方法,其中包含了制作饮料的通用步骤,如烧水、冲泡、倒入杯中和加调料。CoffeeTea 是具体的子类,分别实现了 brewaddCondiments 方法以定制制作咖啡和茶的具体步骤。

    main 方法中,创建了一个咖啡对象和一个茶对象,并分别调用它们的 makeBeverage 方法。你可以运行这个示例来查看模板方法模式的实际应用。

  • 相关阅读:
    使用vue开发中一些图片保存的方法
    DataFrame的创建
    【高德地图API】JS高德地图API实现多边形绘画,高德获取多边形提交数据
    mysql的主从复制和读写分离
    U盘恢复怎么做?3个宝藏方法分享!
    React Native for Arcgis 地图开发 LocationDisplayCtrl (十四)
    关于我学前端一年的体验(心得)
    CDN的基本概念
    【高性能计算】HPC概述
    Topaz Video AI参数详解
  • 原文地址:https://blog.csdn.net/liuming690452074/article/details/134410634