企业网站运营,东莞网站建设主要学什么,官网搭建流程,中国建筑装饰网排行目录
前言
一、核心函数式接口
1. Consumer
2. Supplier
3. Function,
二、场景模拟 1.面向对象设计
2. 策略接口实现#xff08;以 Function 接口作为策略#xff09;
三、对比 前言 在 Java 8 中引入了Stream API 新特性#xff0c;这使得函数式编程风格进…
目录
前言
一、核心函数式接口
1. Consumer
2. Supplier
3. Function,
二、场景模拟 1.面向对象设计
2. 策略接口实现以 Function 接口作为策略
三、对比 前言 在 Java 8 中引入了Stream API 新特性这使得函数式编程风格进一步得到巩固其中伴随着Lambda 表达式和 Stream API 的广泛使用另一种函数式接口风格亦可以简化代码提升可读性和拓展性具体如下
一、核心函数式接口
1. ConsumerT
定义了一个接受单一输入参数并且无返回值的操作。常用于数据处理流程中的消费型操作如打印日志、更新数据库等。 ListString names Arrays.asList(Alice, Bob, Charlie);names.forEach(e- System.out.println(Welcome login : e));// 这里是使用的ConsumerString,给一个参数执行相关操作// 或者定义一个自定义ConsumerConsumerString logAction name - System.out.println(Logging action for: name);names.forEach(logAction);
2. SupplierT
定义了一个不接受任何参数但是会产生一个结果的方法引用。常用于提供数据来源或计算某个值。 SupplierInteger randomIntSupplier () - ThreadLocalRandom.current().nextInt(1, 100);System.out.println(randomIntSupplier.get()); // 输出一个1到100之间的随机整数
3. FunctionT, R
定义了一个接受一个输入参数并产生一个输出结果的方法引用。常用于数据转换、映射或计算。 ListInteger numbers Arrays.asList(1, 2, 3, 4, 5);ListDouble doubles numbers.stream().map((FunctionInteger, Double) Integer::doubleValue).collect(Collectors.toList());doubles.forEach(System.out::println);// 或者自定义FunctionFunctionString, String upperCaseTransformer String::toUpperCase;String transformed upperCaseTransformer.apply(hello); // 输出 HELLOSystem.out.println(transformed);
二、场景模拟 1.面向对象设计 比如常见的促销活动中不同的促销策略计算出商品的最终价格是不一样的采用传统的面向对象设计的话需要为每一个促销活动创建独立的方法或者类了并在购物车类中通过直接调用相应的方法计算如下
public class ShoppingCart {//购物车中的商品列表private ListProduct products;//普通不打折统计所有商品的价格即可public double calculateTotalPriceWithNormalPrice() {double totalPrice products.stream().map(Product::getPrice).reduce(0.0, Double::sum);return totalPrice;}//促销打九折统计商品价格的九折public double calculateTotalPriceWithTenPercentDiscount() {double totalPrice products.stream().map(product - product.getPrice() * 0.9).reduce(0.0, Double::sum);return totalPrice;}//促销直减50 小于0 的按照0元计算public double calculateTotalPriceWithFiftyDollarsOff() {double totalPrice products.stream().map(product - Math.max(product.getPrice() - 50.0, 0.0)).reduce(0.0, Double::sum);return totalPrice;}// 调用示例public void processCheckout(CheckoutType type) {switch (type) {case NORMAL_PRICE:double normalPrice calculateTotalPriceWithNormalPrice();// 处理正常价格结算逻辑break;case TEN_PERCENT_DISCOUNT:double tenPercentDiscount calculateTotalPriceWithTenPercentDiscount();// 处理九折结算逻辑break;case FIFTY_DOLLARS_OFF:double fiftyDollarsOff calculateTotalPriceWithFiftyDollarsOff();// 处理直减50美元结算逻辑break;}}// 其他方法...
}enum CheckoutType {NORMAL_PRICE,TEN_PERCENT_DISCOUNT,FIFTY_DOLLARS_OFF
} 这种方式增加了代码的耦合度并且如果需要新增或者修改促销策略就需要修改ShoppingCart类
2. 策略接口实现以 Function 接口作为策略
import java.util.function.Function;public interface PromotionStrategy extends FunctionDouble, Double {// 不需要额外的方法因为Function本身就是一种策略接受一个参数返回一个结果它接受原始价格并返回打折后的价格
} 创建几个具体的策略实现
public class NormalPriceStrategy implements PromotionStrategy {Overridepublic Double apply(Double originalPrice) {return originalPrice; // 正常价格不做打折处理}
}public class TenPercentDiscountStrategy implements PromotionStrategy {Overridepublic Double apply(Double originalPrice) {return originalPrice * 0.9; // 打九折}
}public class FiftyDollarsOffStrategy implements PromotionStrategy {Overridepublic Double apply(Double originalPrice) {return Math.max(originalPrice - 50.0, 0.0); // 直减50美元价格不能低于0}
} 之后在购物车计算逻辑中可以根据用户选择的促销策略动态计算商品的价格
public class ShoppingCart {private ListProduct products;private PromotionStrategy promotionStrategy;public ShoppingCart(PromotionStrategy strategy) {this.promotionStrategy strategy;// 初始化产品列表...}public double calculateTotalPrice() {double totalPrice products.stream().map(Product::getPrice).map(promotionStrategy).reduce(0.0, Double::sum);return totalPrice;}// 其他方法...
}// 使用示例
ShoppingCart cart new ShoppingCart(new TenPercentDiscountStrategy());
// 添加商品到cart...
double finalPrice cart.calculateTotalPrice(); // 根据策略计算总价 这个例子就是使用 PromotionStrategy 扮演了策略角色不同的折扣策略通过实现 FunctionDouble,Double 接口来决定如何计算折扣价在使用时可以根据需要选择并注入不同的策略实现。
三、对比
策略模式面向对象设计优点 开放封闭原则策略模式鼓励对扩展开放对修改封闭。当需要增加新的促销策略时只需要增加一个新的策略类不需要修改现有的购物车类或者其他已有代码。代码复用每个策略类如NormalPriceStrategy、TenPercentDiscountStrategy、FiftyDollarsOffStrategy可以独立于购物车类使用增强了代码的复用性。低耦合购物车类与具体的促销策略解耦使得系统更灵活更容易维护。 对于简单的场景直接在购物车类中添加多个计算方法直观易懂初学者更容易接受。缺点 策略种类增多时可能会导致策略接口的家族变得庞大若策略逻辑差异不大可能会造成代码冗余。 耦合度高购物车类与具体的促销逻辑紧密耦合当促销策略发生变化时必须修改购物车类的代码。扩展困难若促销策略种类增加会导致购物车类的代码臃肿且不利于代码维护。代码复用性差对于每一种新的促销活动都需要在购物车类中添加新的方法无法直接复用现有逻辑。 其实不难看出在面对频繁变化的业务逻辑如促销策略时策略模式的优势明显它有助于代码的可维护性、扩展性和复用性。而在简单、固定的场景下直接在购物车类中硬编码计算逻辑可能显得更为直接简单。然而考虑到长期的软件迭代和维护成本推荐采用策略模式来优化代码结构。
文末 文章到这里就结束了~