开发者

Data set for storing objects in java

Let's say I have multiple Objects to be stored:

Person ------------ Employee ------------ Sales Engineer       
  |                    |
Customer          Field Engineer

So: Person, Customer, Employ开发者_如何学运维ee, Sales Engineer, Field Engineer.

I need to keep track of all of these...what is the best way to store them? In an ArrayList? A custom ArrayList?

The way they are stored also may affect future expansion - in the future, these objects might be generated by fields from an SQL Server. (Also, this is an Android App - so that could be a factor.)


You'll want a List<Person>. Your diagram suggests inheritance, so you'll want to have a collection of the super class and let polymorphism do the rest.

Your code can do this:

List<Person> people = new ArrayList<Person>();
// Any class that extends person can be added
people.add(new Customer());
people.add(new FieldEngineer());
for (Person person : people) {
    System.out.println(person);
}

Your design as expressed won't allow Engineers to be Customers, or Sales engineers to go into the Field, but that's the curse of inheritance in cases like yours.

A better design, if you need the flexibility, might be to keep the Person class and assign a Person a Role in decorator fashion.

A decorator would add behavior using composition rather than inheritance, like this:

public class Customer {

    private Person person;

    public Customer(Person p) { this.person = p; }

    public void buyIt() { // do something customer like here }
}

public class FieldEngineer {

    private Person person;

    public FieldEngineer(Person p) { this.person = p; }

    public void fixIt() { // do something field engineer like here }
}


Use a heterogenous list -- in java you can use generics like this List <Person>


If you are uncertain about how you will need to access objects in the future you may find that a HashTable <Person> affords a wide degree of flexibility.

Since it uses key-value pairs you can retrieve a specific object quickly and the .keys() method offers a means to traverse the entire set iteratively if you find that necessary.


I am assuming all of the objects are a part of a set?

Ideally, the Person should have a get/setCustomer and the Employee should have a get/setFieldEngineer and then the structure should be something like:

class CustomerRelationship{
    public Employee employee;
    public SalesEngineer salesEngineer;
    public Person customer;
}

If the objects are not parts of a set, but are a list of Object, then you might want to reconsider your design. Or you could use instanceof everywhere ( bad ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜