gpt4 book ai didi

java - 我应该将 java Stream.map 函数与 switch 语句一起使用吗?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:38:51 30 4
gpt4 key购买 nike

我想根据类型将对象流传输到不同的对象。例如:

Stream<Animal> animals = Arrays.stream(Arrays.asList(new Animal("A"),new Animal("B")));
Stream result = animals.map(animal) ->{
switch (animal.getType()) {
case "A" : return new Bird(animal);
case "B" : return new LION(animal);
case "C" : return new Tiger(animal);
case "D" : return new FISH(animal);
}
}

这是函数式编程的“反模式”吗?

我能否通过函数式编程以不同方式实现上述目标?

(备注:我也不喜欢每次添加新类型时都必须更新所有 switch 语句)

最佳答案

@TimB 在其 answer 中是正确的.这与函数式编程无关。

正如您所说:

every time I add a new type I have to update all my switch statements

您的“工厂 lambda”正在打破 Open/closed principle :

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

您可以按照以下原则创建这个动物工厂:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;

public class AnimalFactory {
private final Map<String, Function<Animal, Object>> delegateFactories
= new HashMap<String, Function<Animal,Object>>();

public AnimalFactory withFactory(String type, Function<Animal, Object> factory) {
delegateFactories.put(type, factory);
return this;
}

public Object createAnimal(Animal animal) {
return delegateFactories.get(animal.getType()).apply(animal);
}
}

您可以通过 taking advantage of java 8 feature 让他们轻松使用它:

public static void main(String[] args) {
Stream<Animal> animals = Arrays.asList(new Animal("A"),new Animal("B")).stream();
AnimalFactory animalFactory = new AnimalFactory();
animalFactory.withFactory("A", Bird::new);
animalFactory.withFactory("B", Lion::new);
animalFactory.withFactory("C", Tiger::new);
animalFactory.withFactory("D", Fish::new);

Stream result = animals.map(animalFactory::createAnimal);
}

关于java - 我应该将 java Stream.map 函数与 switch 语句一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25075389/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com