简体   繁体   中英

Using an interface and dependency injection

I have a program that needs to read data from a number of sources. I have several objects, each containing a list of students and their test scores. I then have another class which must extract all the information from each object.

The problem is that I must operate through an interface. ie

public class Total{
      HashMap<String, Integer> results; 
      ScoresInterface si;
      ...
      void addScores(){
         results.putAll( si.getScores());
      }

}

public interface ScoresInterface{
       public HashMap getScores();
}

public class Scores implements ScoresInterface{
     HashMap<String, Integer> results;
     ...
     public HashMap getScores(){
            return results;
      }
}

I hope this code makes sense. The Total class basically needs to access a number of Scores objects and collect all the information.

My question is basically, how can I let the Total class know about all the objects of the scores class? I have thought about adding a function in Total called setSource(ScoresInterface a) and passing each new object of Scores in. However, it seems a bit long winded. What if there are 100 objects.

Thanks for any help

I would pass in a List<ScoresInterface> .

That way you could use the Total class to iterate through and calculate the total.

The type of List implementation (ArrayList, LinkedList etc..) is up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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