假设我有多个要存储的对象:
Person ------------ Employee ------------ Sales Engineer | | Customer Field Engineer所以:人员,客户,员工,销售工程师,现场工程师。
我需要跟踪所有这些......存储它们的最佳方式是什么? 在ArrayList中? 自定义ArrayList?
它们的存储方式也可能影响将来的扩展 - 将来,这些对象可能由SQL Server的字段生成。 (另外,这是一个Android应用程序 - 因此可能是一个因素。)
Let's say I have multiple Objects to be stored:
Person ------------ Employee ------------ Sales Engineer | | Customer Field EngineerSo: Person, Customer, Employee, 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.)
最满意答案
你会想要一个List<Person> 。 您的图表显示了继承,所以您需要拥有超类的集合,并让剩余的多态。
您的代码可以执行此操作:
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); }您所表达的设计不允许工程师成为客户,或销售工程师进入现场,但这是像您这样的情况下的继承诅咒。
如果您需要灵活性,更好的设计可能是保留Person类并为装饰者分配Person角色。
装饰者会使用组合而不是继承来添加行为,如下所示:
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 } }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 } }更多推荐
发布评论