简体   繁体   English

在这种情况下如何避免使用switch语句

[英]How can I avoid switch statement in this case

I want to avoid using a switch statement but I don't know how. 我想避免使用switch语句,但是我不知道如何。 This is my problem: 这是我的问题:

public class Person{
    String status;

    public void doSomething(){
        switch (status) {
        case "hungry":
                eatSomething();
                status = "full";
            break;
        case "full":
                doNothing();
                status = "hungry";
        default:
            break;
        }
    }}

I want to do something like this: 我想做这样的事情:

    public abstract class Person{
        public abstract void doSomething();
}

public class HungryPerson extends Person{
        @Override
        public void doSomethink() {
            eatSomething();
        }
}


public class FullPerson extends Person{
    @Override
    public void doSomething() {
            doNothing();
    }   
}

The problem is: if the Person ate something then he has to be FullPerson , but if I had a reference with HungryPerson how can I change it to FullPerson ? 问题是:如果该Person吃了东西,那么他必须是FullPerson ,但是如果我有HungryPerson如何将其更改为FullPerson

int main(){
    Person person = new HungryPerson();
    person.doSomething();
    //I want to person contain a FullPerson reference.
}

Actually, your first implementation is better from an Object Oriented point of view. 实际上,从面向对象的角度来看,您的第一个实现更好。 The state of the object can change but the object itself is still the same object. 对象的状态可以更改,但是对象本身仍然是同一对象。 You remain the same person even when you are hungry or after you eat. 即使您饿了或吃饭后,您仍然是同一个人。 You might want to use an Enum instead of a String for the status. 您可能要使用Enum而不是字符串作为状态。

use an if/else. 使用if / else。

if(status == "hungry")
     doSomething();

doSomethingElse();

instead of using the switch statement, you can use if-else. 除了使用switch语句,还可以使用if-else。 you can use if(status.equals("hungry")) to check if the status of the person is hungry or not and then call the respective methods as you want. 您可以使用if(status.equals(“ hungry”))检查人员的状态是否饥饿,然后根据需要调用相应的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM