如何避免很多 if else 条件 [英] How to avoid a lot of if else conditions

查看:45
本文介绍了如何避免很多 if else 条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多关于代码重构和避免 if else 语句的主题.实际上,我有一堂课使用了很多 if - else 条件.

I have read a lot of topics about code refactoring and avoiding of if else statements. Actually, I have a class where I am using a lot of if - else conditions.

更多细节:我正在使用 pull 解析器,在我的soap 响应的每一行上,我将检查是否有我感兴趣的标签,如果没有,请检查另一个标签等:

More details: I am using the pull parser and on each line of my soap response, I will check if there is a tag I am interested on, if not, check another tag etc:

 if(eventType == XmlPullParser.START_TAG) {
            soapResponse= xpp.getName().toString();
            
            if (soapResponse.equals("EditorialOffice")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialOffice += xpp.getText();
                }
            }   
            else if (soapResponse.equals("EditorialBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                editorialBoard += xpp.getText();
                }
            }
            else if (soapResponse.equals("AdvisoryBoard")){  
                eventType = xpp.next();
                if (xpp.getText()!=null){
                advisoryBoard += xpp.getText();
                }
            }   
        }
        eventType = xpp.next();
     }

现在,我想用别的东西,而不是那些 if else 条件,但我不知道是什么.

Now, I would like to use something else, instead of those if else conditions, but I don't know what.

可以举个例子吗?

推荐答案

尝试查看策略模式.

  • 制作一个接口类来处理响应(IMyResponse)
    • 使用此 IMyResponse 创建 AdvisoryBoardResponse、EditorialBoardResponse 类

    小例子:

    // Interface
    public interface IResponseHandler {
       public void handleResponse(XmlPullParser xxp);
    
    }
    
    // Concrete class for EditorialOffice response
    private class EditorialOfficeHandler implements IResponseHandler {
       public void handleResponse(XmlPullParser xxp) {
           // Do something to handle Editorial Office response
       }
    }
    
    // Concrete class for EditorialBoard response
    private class EditorialBoardHandler implements IResponseHandler {
       public void handleResponse(XmlPullParser xxp) {
           // Do something to handle Editorial Board response
       }
    }
    

    在需要创建处理程序的地方:

    On a place you need to create the handlers:

    Map<String, IResponseHandler> strategyHandlers = new HashMap<String,IResponseHandler>();
    strategyHandlers.put("EditorialOffice", new EditorialOfficeHandler());
    strategyHandlers.put("EditorialBoard", new EditorialBoardHandler());
    

    您在何处收到回复:

    IResponseHandler responseHandler = strategyHandlers.get(soapResponse);
    responseHandler.handleResponse(xxp);
    

    这篇关于如何避免很多 if else 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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