我在 Matten 和 Codemwnci 的回答中放了一些 cmets,下面是对它们的解释。
Codemwnci 建议您不应该在不设置目录的情况下构建项目。
public class Item {
public Item(Catalog catalog) {
// set up item here
// finally add item to the catalog
catalog.addAnItem(this);
}
}
此显式构造函数删除了隐式默认(无参数)构造函数,如果没有有效的非空目录,您将无法构造项目。
如果您有各种类型的物品,具有(略微)不同的行为,那么 Matten 的回答可能会更好地为您服务(尽管此处略有更改)。
作为一个例子,我正在使用一本书(这是你的项目)。我的书有标题、作者、textAtTheBack 和权重。
interface Book {
String getTitle();
String getAuthor();
String getTextAtTheBack();
Long getWeight(); // in grams, can be very heavy!
}
public class Catalog {
private ArrayList<Book> catalogue;
public Book createPaperback(final String title, final String author,
final String tatb, final Long weight) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return weight;}
}
catalogue.add(b);
return b;
}
public Book createEBook(final String title, final String author,
final String tatb) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return 0;} // Yep - no weight!
}
catalogue.add(b);
return b;
}
}
或者,您可以有不同的目录:
public abstract class Catalogue {
private final List<Book> books = new ArrayList<Book>;
public abstract Book (final String title, final String author,
final String tatb, final Long weight);
/** Find the book with the given title (not null) in the current catalogue.
* @return the book, or null if not found.
*/
public void findBook(String title) {
for (Book b : books) {
if (b.getTitle().equalsIgnoreCase(title)) {
return b;
}
}
return null;
}
protected void addBookToCatalogue(Book b) {
books.add(b);
}
}
public class EbookCatalogue extends Catalogue {
public Book (final String title, final String author,
final String tatb, final Long weight) {
Book b = new Book() {
String getTitle() { return title; }
String getAuthor() {return author; }
String getTextAtTheBack() {return tatb;}
Long getWeight() {return 0;} // ignore weight
}
addBookToCatalogue(b);
return b;
}
}
在程序的其余部分中,您可以有多个目录,每个目录的图书类型略有不同,但程序不需要知道这一点。
我认为在这种情况下,codemwnci 的简单构造函数是最好的,但如果您的情况需要更灵活的解决方案,还有其他解决方案。