0
点赞
收藏
分享

微信扫一扫

java代替Switch 的方法

Fifi的天马行空 2023-07-14 阅读 68

Java代替Switch的方法

在Java编程中,我们经常使用switch语句来根据不同的条件执行不同的代码块。然而,当有大量的条件需要判断时,switch语句会变得冗长而且难以维护。幸运的是,Java提供了一些替代switch语句的方法,使代码更加简洁和可读性更强。

1. 使用多态

多态是面向对象编程的重要概念之一,它允许我们根据对象的实际类型来执行不同的操作。我们可以利用这种特性来代替switch语句。

interface Animal {
    void makeSound();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Cat meows");
    }
}

class Main {
    public static void main(String[] args) {
        Animal animal = getAnimal("Dog");
        animal.makeSound();
    }
    
    public static Animal getAnimal(String type) {
        if (type.equals("Dog")) {
            return new Dog();
        } else if (type.equals("Cat")) {
            return new Cat();
        }
        
        throw new IllegalArgumentException("Invalid animal type: " + type);
    }
}

在上面的代码中,我们定义了一个Animal接口和两个实现了该接口的类DogCat。通过传递不同的参数到getAnimal方法,我们可以获取不同类型的动物对象。然后,我们可以直接调用makeSound方法,而无需使用switch语句。这种方式使得代码更加灵活和可扩展,我们可以轻松地添加新的动物类型,而无需修改现有的代码。

2. 使用Map

另一种代替switch语句的方法是使用Map数据结构。我们可以将条件和对应的操作存储在Map中,然后根据条件从Map中获取对应的操作。

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

class Main {
    public static void main(String[] args) {
        Map<String, Consumer<String>> actions = new HashMap<>();
        actions.put("Dog", (name) -> System.out.println(name + " barks"));
        actions.put("Cat", (name) -> System.out.println(name + " meows"));
        
        String animalType = "Dog";
        String animalName = "Bobby";
        
        actions.get(animalType).accept(animalName);
    }
}

在上面的代码中,我们创建了一个Map对象actions来存储条件和对应的操作。我们使用Consumer函数式接口来表示动作,它接受一个参数并执行相应的操作。通过调用actions.get(animalType).accept(animalName),我们可以根据条件执行相应的操作。这种方式使得代码更加简洁和可读性更强,我们可以轻松地添加新的条件和操作,而无需修改现有的代码。

3. 使用策略模式

策略模式是一种常见的设计模式,它允许在运行时选择算法的行为。我们可以使用策略模式代替switch语句,将每种条件和对应的算法封装成一个策略类,然后根据条件选择相应的策略。

interface Animal {
    void makeSound();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Cat meows");
    }
}

class AnimalStrategy {
    private Animal animal;
    
    public AnimalStrategy(String type) {
        if (type.equals("Dog")) {
            animal = new Dog();
        } else if (type.equals("Cat")) {
            animal = new Cat();
        } else {
            throw new IllegalArgumentException("Invalid animal type: " + type);
        }
    }
    
    public void makeSound() {
        animal.makeSound();
    }
}

class Main {
    public static void main(String[] args) {
        AnimalStrategy animalStrategy = new AnimalStrategy("Dog");
        animalStrategy.makeSound();
    }
}

在上面的代码中,我们定义了一个AnimalStrategy类来封装不同的动物策略。通过传递不同的参数到AnimalStrategy

举报

相关推荐

0 条评论