我已经把在Matten和Codemwnci的回答一些评论,这里是他们的解释。
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的简单构造函数是最好的,但如果您的情况需要更灵活的解决方案,可以使用其他解决方案。
这样做可以完成工作,并且如果我当天没有投票,那么会得到+1。但是,值得注意的是,这将您限制为单个目录。单身人士通常被认为是反模式。 – corsiKa 2011-02-17 20:05:41
@glowcoder - 你的意思是实现单例模式,是吗?使用工厂模式允许多个目录(和多个catalgues中的项目),因此这是我的第一个想法:) – Matten 2011-02-17 20:07:59
为了清楚起见:这是目录中的一种方法。如果不调用目录的createItem(),你就不应该创建一个Item。可能通过使Item构造函数包受保护或将Item定义为接口,并让createItem实例化Item的匿名内部类实现。如果这太快了(对于威尔在这个阶段),不要打扰:) – extraneon 2011-02-17 20:08:38