改变调用类的不同实例的方法的顺序

2022-09-02 19:26:19

根据某些条件操纵事情完成顺序的最佳方法是什么(除了用不同的顺序再次编写它们)?

假设有一个 Person 类,Person 的每个对象都表示一个不同的人。

class Person{
    int eatingPriority = 3;
    int sleepingPriority = 2;
    int recreationPriority = 1;

    void eat() {/*eats*/}
    void sleep() {/*sleeps*/}
    void watchTv() {/*watches tv*/}

    void satisfyNeeds() {
        //HOW TO DO THIS
    }
}

如何使方法根据其优先级调用其他三个方法?satisfyNeeds()

注意:我想明确一点,优先级可以从一个人到另一个人而变化。


答案 1

您可以使用 1 个类和 1 个接口执行此操作。

public class Person {
    int eatingPriority = 3;
    int sleepingPriority = 2;
    int recreationPriority = 1;

    PriorityQueue<Action> actions;

    void eat() { }

    void sleep() { }

    void watchTv() { }

    public Person() {
        actions = new PriorityQueue<Action>(new Comparator<Action>() {
            @Override
            public int compare(Action o1, Action o2) {
                return o2.getPriority() - o1.getPriority();
            }
        });

        actions.add(new Action() {
            @Override
            public int getPriority() {
                return eatingPriority;
            }
            @Override
            public void execute() {
                eat();
            }
        });

        actions.add(new Action() {
            @Override
            public int getPriority() {
                return sleepingPriority;
            }
            @Override
            public void execute() {
                sleep();
            }
        });

        actions.add(new Action() {
            @Override
            public int getPriority() {
                return recreationPriority;
            }
            @Override
            public void execute() {
                watchTv();
            }
        });
    }

    public void satisfyNeeds() {
        for (Action action : actions) {
            action.execute();
        }
    }

    interface Action {
        public int getPriority();
        public void execute();
    }
}

答案 2

这是另一种可能的实现:

abstract class Need {
  abstract void satisfy();
}

class Eat extends Need {
  @Override
  public void satisfy() { /* eat ...*/}
}

class Sleep extends Need {
  @Override
  public void satisfy() { /* sleep ...*/}
}

class DrinkBeer extends Need {
  @Override
  public void satisfy() { /* drink beer ...*/}
}

class Person{
  // TreeMap will sort the map in the key's natural order (a int here)
  private Map<Integer, Need> needs = new TreeMap<>();    

 Person() {
   add(new Eat(), 3);
   add(new Sleep(), 2);
   add(new DrinkBeer(), 1);
 }

 void add(Need need, int priority) {
   needs.put(Integer.valueOf(priority), need);
 }

 void satisfyNeeds() {
    for(Need need : needs.values())
      need.satisfy();
  }
}