java—基于对象的字段值,对对象的不同操作使用哪种oop设计模式?

ffvjumwh  于 2021-07-23  发布在  Java
关注(0)|答案(4)|浏览(353)

数据库里有实体,比如说,monthplan:

class MonthPlan {
    private boolean approved;

    // other fields
}

还有一个rest接口,它接受基于程序更改实体示例的外部请求。例如,请求

class EditMonthPlanRequest {
    private long amount;

    // other fields
}

用于更改月计划金额。
我需要的是执行不同的行动 MonthPlan 基于价值的实体 approved 现场。例如,上述请求的代码可以如下所示

MonthPlan plan = getPlan(...);
if (plan.isApproved()) {
    // actions using data from EditMonthPlanRequest
} else {
    // other actions using data from EditMonthPlanRequest
}

将有5-6个不同的请求,每个请求正好有两个基于 approved 编辑实体的字段。对于这样的用例,我可以使用什么oop设计模式来编写更简洁的代码?

py49o6xq

py49o6xq1#

我不认为你需要在这样一个简单的情况下设计模式。每个请求将由服务层的相应方法进行处理。

5f0d552i

5f0d552i2#

对于这种简单的情况,模板方法模式可能适用于:

abstract class AbstractRequest {

  public void execute(...){
    MonthPlan plan = getPlan(...);
    if (plan.isApproved()) {
      executeForApproved(plan);
    } else {
      executeForNonApproved(plan);
    }
  }

  protected abstract void executeForApproved(MonthPlan plan);

  protected abstract void executeForNonApproved(MonthPlan plan);
}

这样,就不需要在每个子类中重复if语句和getplan(…):

class EditMonthPlanRequest extends AbstractRequest {
  private long amount;
  // other fields

  protected void executeForApproved(MonthPlan plan){
     ...
  }

  protected void executeForNonApproved(MonthPlan plan){
     ...
  }

}
yuvru6vn

yuvru6vn3#

如果您想执行oop,那么就用多态性替换条件。
在这个例子中,它意味着分裂 MonthPlan 一分为二。
class ApprovedMonthPlan extends MonthPlan class UnapprovedMonthPlan extends MonthPlan 每个类处理 EditMonthPlanRequest 以自己的方式。

eoigrqb6

eoigrqb64#

在这种情况下,状态模式更合适。
当对象基于其内部状态更改其行为时,将使用状态设计模式。
如果必须根据对象的状态更改其行为,则可以在对象中使用状态变量,并使用if else条件块根据状态执行不同的操作。状态模式用于提供一种系统的、失去耦合的方式,通过上下文和状态实现来实现这一点。
尝试根据您的描述实施:

public class StatePattern {

    public static void main(String[] args) {
        MonthPlan monthPlan = null; //= new MonthPlan(...)
        StateContext stateContext = new StateContext();
        if(monthPlan.isApproved()) {
            stateContext.setState(new Approved());
        }else {
            stateContext.setState(new NotApproved());
        }
    }
}

class MonthPlan {
    private boolean approved;

    public boolean isApproved() {
        return approved;
    }
    // other fields
}

interface State{
    public void doAction(StateContext ctx);
}

class StateContext{
    private State currentState;

    public StateContext() {
        //default Approved state, you can change if you want
        currentState = new Approved(); 
    }

    public void setState(State state) {
        currentState = state;
    }

    public void doAction() {
        currentState.doAction(this);
    }

}

class Approved implements State{
    @Override
    public void doAction(StateContext ctx) {
        //actions using data from EditMonthPlanRequest
    }
}

class NotApproved implements State{
    @Override
    public void doAction(StateContext ctx) {
         //other actions using data from EditMonthPlanRequest
    }
}

相关问题