避免使用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结构,使代码更易读、可维护和可扩展。

相关内容

热门资讯

透视系统!wepoker透视脚... 透视系统!wepoker透视脚本网页,wpk作弊最怕三个东西,可靠技巧(本来是真的有挂);亲们利用一...
透视好友房!wepoker透视... 透视好友房!wepoker透视底牌脚本,德普之星透视辅助软件,微扑克教程(素来真的有挂)需要回顾用户...
透视科技!红龙poker脚本,... 透视科技!红龙poker脚本,德普之星透视辅助软件,wepoke教程(先前有挂);德普之星透视辅助软...
透视免费!德普之星透视辅助软件... 透视免费!德普之星透视辅助软件下载,sohoo poker辅助,揭秘教程(果然有挂);原来确实真的有...
透视模拟器!wepoker辅助... 1、透视模拟器!wepoker辅助透视软件,拱趴大菠萝有挂吗,透牌教程(本然存在有挂);详细教程。2...
透视黑科技!aapoker透视... 透视黑科技!aapoker透视插件下载,hhpoker哪个俱乐部靠谱,黑科技教程(从来真的有挂)关于...
透视最新!aapoker脚本怎... 透视最新!aapoker脚本怎么用,poker红龙辅助,德州教程(真是有挂)1、点击下载安装,微扑克...
透视透视!红龙poker作弊指... 透视透视!红龙poker作弊指令,拱趴大菠萝作弊方法,2025新版技巧(其实真的有挂);支持2-10...
透视软件!wpk辅助插件叫什么... 透视软件!wpk辅助插件叫什么,聚星ai辅助工具下载,科技教程(原生真的是有挂)1、完成wpk辅助插...
透视最新!wpk透视脚本链接,... 透视最新!wpk透视脚本链接,如何下载wpk透视版,德州论坛(先前存在有挂);致您一封信;亲爱wpk...