避免使用if / switch case结构可以通过使用多态、策略模式、工厂模式等技术来实现。下面是一些解决方法的代码示例:
interface Animal {
void makeSound();
}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("汪汪汪");
}
}
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("喵喵喵");
}
}
// 在其他类中使用Animal接口来调用具体的实现类
Animal animal = new Dog();
animal.makeSound(); // 输出:汪汪汪
animal = new Cat();
animal.makeSound(); // 输出:喵喵喵
interface DiscountStrategy {
double applyDiscount(double originalPrice);
}
class TenPercentDiscountStrategy implements DiscountStrategy {
@Override
public double applyDiscount(double originalPrice) {
return originalPrice * 0.9;
}
}
class TwentyPercentDiscountStrategy implements DiscountStrategy {
@Override
public double applyDiscount(double originalPrice) {
return originalPrice * 0.8;
}
}
// 在其他类中使用DiscountStrategy接口来调用具体的策略
DiscountStrategy strategy = new TenPercentDiscountStrategy();
double discountedPrice = strategy.applyDiscount(100); // 输出:90
strategy = new TwentyPercentDiscountStrategy();
discountedPrice = strategy.applyDiscount(100); // 输出:80
interface Shape {
void draw();
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("画圆形");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("画矩形");
}
}
class ShapeFactory {
public Shape createShape(String shapeType) {
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
// 在其他类中使用ShapeFactory来创建具体的Shape对象
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape = shapeFactory.createShape("CIRCLE");
shape.draw(); // 输出:画圆形
shape = shapeFactory.createShape("RECTANGLE");
shape.draw(); // 输出:画矩形
通过使用多态、策略模式或工厂模式,我们可以消除繁琐的if / switch case结构,使代码更易读、可维护和可扩展。