从子类中提取逻辑

时间:2018-10-05 12:45:16

标签: spring

当前,我有以下模型:

public abstract class MyClass {

   public abstract boolean validate();

}

public class MyClassImpl1 extends MyClass {

   ....

   public abstract boolean validate() {
      ... // Do something
   }

}

public class MyClassImpl2 extends MyClass {

   ...

   public abstract boolean validate() {
      ... // Do something different
   }

}

然后在代码中的某处使用MyClass

MyClass myClass = ...;

boolean valid = myClass.validate();

大多数程序员都认为应用程序逻辑不应包含在数据模型中,因此我试图理解如何在不破坏我的通用方法的情况下将validate的逻辑提取到@Service中(以及而不使用instanceof之类的东西!)

有可能吗?

1 个答案:

答案 0 :(得分:0)

好的,找到了解决方法:https://en.wikipedia.org/wiki/Visitor_pattern

有效地:

public abstract class MyClass {

   public abstract boolean validate();

}

public class MyClassImpl1 extends MyClass {

   ....

   public boolean validate(ValidatorService validator) {
      return validator.validate(this);
   }

}

public class MyClassImpl2 extends MyClass {

   ...

   public boolean validate(ValidatorService validator) {
      return validator.validate(this);
   }

}

@Service
public class ValidatorService {

   public boolean validate(MyClass myClass) {
      return myClass.validate(this);
   }

   public boolean validate(MyClassImpl1 myClassImpl1) {
      // Do something
      return false;
   }

   public boolean validate(MyClassImpl2 myClassImpl12) {
      // Do something else
      return false;
   }
}

现在您可以在validatorService.validate(myClass)的任何地方致电myClass.validate(validatorService)@Autowire ValidatorService validatorService