简体   繁体   English

需要帮助以避免类型转换

[英]Need help to avoid type casting

I need help in refactoring the following piece of code . 在重构以下代码时,我需要帮助。 There are 2 main problems that I want to fix in this code 1. Unsafe type casting in Rule1 implementation 2. Implementation of too many interfaces 我要在此代码中解决两个主要问题:1. Rule1实现中的不安全类型转换2.实现太多接口

  public interface Rule {
     public void execute(DataProvider dataProvider);
  }

  public interface DataProvider {
     // No common functions as of now 
  }

  public interface Rule1dataProvider extends DataProvider {
     // Functions required by Rule1
  }

  public class Rule1 implements Rule {
     public void execute(DataProvider dataProvider) {
       ADataProvider rule1DataProvider = <ADataProvider>dataProvider;
       // Other logic 
    }
  }

 public class EntityADataProvider implements Rule1DataProvider, Rule2DataProvider... {
    // Overrides functions of Rule 1 and Rule2 
 }

I was trying to use generics here, but could not figure out the right way to use them in order to eliminate the type casting 我在这里尝试使用泛型,但无法找出正确的使用方式来消除类型转换

Make Rule generic: 使规则通用:

public interface Rule<T extends DataProvider> {
    public void execute(T dataProvider);
}

And then 接着

public class Rule1 implements Rule<Rule1dataProvider> {
    @Override
    public void execute(Rule1dataProvider dataProvider) {            
        // ...
    }
}

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

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