Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. public static DataSource parseData(InputStream contents, String identifier)
  2.  
  3. public static DataSource parseData(InputStream contents, String identifier) {
  4. if (DataSource1.respondsTo(identifier) {
  5. return new DataSource1(contents);
  6. }
  7. //more ifs. There likely will be about 20 of those.
  8. }
  9.  
  10. interface DataSource {
  11. boolean respondsTo(String identifier)
  12. }
  13.  
  14. class DataSource1 implements DataSource {
  15. DataSource1(InputStream is) { /* magic goes here */ }
  16. @Override boolean respondsTo(String identifier) { identifier in ["DS1 idX", "DS1 idY", "DS1 idZ"] }
  17. }
  18.  
  19. class DataSource2 implements DataSource {
  20. DataSource2(InputStream is) { /* magic goes here */ }
  21. @Override boolean respondsTo(String identifier) { identifier in ["DS2 idX", "DS2 idY", "DS2 idZ"] }
  22. }
  23.  
  24. // ...
  25.  
  26. class DataSource20 implements DataSource {
  27. DataSource20(InputStream is) { /* magic goes here */ }
  28. @Override boolean respondsTo(String identifier) { identifier in ["DS20 idX", "DS20 idY", "DS20 idZ"] }
  29. }
  30.  
  31. enum DataSourceEnum {
  32. ds1 (["DS1 idZ", "DS1 idY", "DS1 idZ"], { is -> new DataSource1(is) }),
  33. ds2 (["DS1 idZ", "DS1 idY", "DS1 idZ"], { is -> new DataSource2(is) }),
  34.  
  35. // ...
  36.  
  37. ds20 (["DS20 idX", "DS20 idY", "DS20 idZ"], { is -> new DataSource20(is) })
  38.  
  39. private final static Map<String, DataSourceEnum> dsMapping = [:]
  40.  
  41. final Closure<DataSource> buildDataSource
  42.  
  43. private DataSourceEnum(List<String> identifiers, Closure<DataSource> ctor) {
  44. DataSourceEnum.dsMapping += identifiers.collectEntries { id -> [(id):this] }
  45. this.buildDataSource = ctor
  46. }
  47.  
  48. static DataSourceEnum identify(String id) { dsMapping[id] }
  49. }
  50.  
  51. DataSource parseData(InputStream contents, String identifier) {
  52. DataSourceEnum.identify(identifier)?.buildDataSource(contents)
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement