避免使用if / switch case结构以使代码更易读
创始人
2024-12-16 15:00:06
0

避免使用if / switch case结构可以通过使用多态、策略模式、工厂模式等技术来实现。下面是一些解决方法的代码示例:

  1. 使用多态:
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(); // 输出:喵喵喵
  1. 使用策略模式:
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
  1. 使用工厂模式:
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结构,使代码更易读、可维护和可扩展。

相关内容

热门资讯

透明辅助!新九哥辅助开挂,we... 您好:新九哥辅助开挂这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...
透视辅助!渝都麻将开挂方法,德... 透视辅助!渝都麻将开挂方法,德州局hhpoker-原生有挂开挂辅助安装您好:渝都麻将开挂方法这款游戏...
透明教程!益乐绍兴辅助,wep... 透明教程!益乐绍兴辅助,wepoker好友助力码-起初有挂开挂辅助脚本 了解更多开挂安装加(1367...
透视游戏!今日长牌破解,hhp... 透视游戏!今日长牌破解,hhpoker软件可以玩吗-从来有挂开挂辅助软件您好:今日长牌破解这款游戏可...
透视代打!呗兔挂透视挂开挂,拱... 透视代打!呗兔挂透视挂开挂,拱趴大菠萝万能挂-一向有挂开挂辅助软件 了解更多开挂安装加(136704...
透明辅助!创思维正版辅助器下载... 创思维正版辅助器下载是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加...
透视ai!麻辣竞技辅助,hhp... 麻辣竞技辅助是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信(...
透视最新!边锋干橙眼ios辅助... 透视最新!边锋干橙眼ios辅助微信,wepoker怎么提高运气-原先有挂开挂辅助软件您好:边锋干橙眼...
透视辅助!多乐游戏辅助脚本ht... 透视辅助!多乐游戏辅助脚本http,wepoker私人局可以透视-原本有挂开挂辅助平台;无需打开直接...
透明黑科技!佛手在线辅助器安卓... 透明黑科技!佛手在线辅助器安卓,aapoker如何设置胜率-本来有挂开挂辅助神器1、下载安装好佛手在...