将许多“if else"语句转换为更简洁的方法 [英] Converting many 'if else' statements to a cleaner approach

查看:32
本文介绍了将许多“if else"语句转换为更简洁的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在这里检测 mimeType 是否等于某个 MIME 类型,如果是,会做一定的转换

My code here detects if the mimeType is equals to some MIME type, if it is, it will do a certain conversion

public void convertToMp3(File src, File target,String mimeType){
    if(mimeType.equals("audio/mpeg")){
        ...
    }else if(mimeType.equals("audio/wav")){
        mp3ToWav();
    }else if(mimeType.equals("audio/ogg")){
        ...
    }else if(...){
    ... //More if and else here
}

我已经缩短了我的代码,因为它有很多else if语句,什么设计模式适合去除很多ifelse> 还是 else if 语句?

I have shortened my code, because it has a lot of else if statements, What design pattern is suitable for removing many if and else or else if statements?

推荐答案

你可以有一个 Converter 接口.然后你可以为每个 Mimetype 创建一个类,如:

You could have a Converter interface. Then you could create a class for each Mimetype like:

public interface Converter {

    public void convertToMp3();
    public void convertToOgg();

}

public class MpegConverter implements Converter {

    public void convertToMp3() {
        //Code here
    }

    public void convertToOgg() {
        //Code here
    }

}

对于每个转换器,您都需要一个这样的类.然后你可以像这样设置地图:

You would need a class like this for each converter. Then you could set up a map like this:

Map<String, Converter> mimeTypeMap = new HashMap<String, Converter>();

mimeTypeMap.put("audio/mpeg", new MpegConverter());

然后你的 convertToMp3 方法变成这样:

Then your convertToMp3 method becomes like this:

Converter converter = mimeTypeMap.get(mimeType);
converter.convertToMp3();

使用这种方法,您可以在未来轻松添加不同的转换器.

Using this approach you could easily add different converters in the future.

所有未经测试,可能无法编译,但您明白了

All untested, probably doesn't compile, but you get the idea

这篇关于将许多“if else"语句转换为更简洁的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆