解决接口实现的实例

时间:2015-03-31 03:46:38

标签: java

例如如果我有一个接口和两个实现类。然后我有基于实现实例验证的类,因为每个都有自己的验证。现在我使用instanceof来解决这个问题。有没有比我写的下面代码更好的方法呢?

    public interface TestService{
         public boolean testMethod();
    }

    public class TestServiceImpA implements TestService{
        public boolean testMethod(){
          return true;
    }
    //some other implementation
    }
    public class TestServiceImpB implements TestService{
        public boolean testMethod(){
          return false;
    }
     //some other implementation
    }

    import org.api.TestService;
    public class ClassB {

       public void methodValidator(TestService service){
    //here I have to write some validation for each type.
    //I have done this like
    if(service instanceof TestServiceImpA)
    {
       TestType testype = TestUtil.getTestType(service.getId());
     //now I need to validate testype based on this instaceof the interface
    }
    if(service instanceof TestServiceImpb)
    {
    }

    }
    }

0 个答案:

没有答案