你如何在子类中有一个单例模式?例如,在 itemCatalog 下面的代码中扩展了 item。我想使用类项目的 getPrice getter
public class ItemCatalog extends Item{
private static ItemCatalog instance = new ItemCatalog();
private Item itemCatalog[] = new Item[9];
private ItemCatalog(){
}
public static ItemCatalog getInstance(){
return instance;
}
public void populateCatalog(){
itemCatalog[0] = new Item("bb","Baked Beans",35);
itemCatalog[1] = new Item("cf","Cornflakes",100);
itemCatalog[2] = new Item("s0","Sugar",50);
itemCatalog[3] = new Item("tb","Tea Bags",115);
itemCatalog[4] = new Item("ic","Instant Coffee",250);
itemCatalog[5] = new Item("b0","Bread",50);
itemCatalog[6] = new Item("s0","Sausages",130);
itemCatalog[7] = new Item("e0","Eggs",75);
itemCatalog[8] = new Item("m0","Milk",65);
}
public void searchCatalog(String itemCode){
for (int i = 0; i < itemCatalog.length; i++){
if (itemCode.equals(itemCatalog[i].getItemCode())){
price = itemCatalog[i].getItemprice();
break;
}
}
}
编辑2:我想让这个类作为一个单例和一个不是单例的项目类的子类。
当我在构造函数中放置 super(String itemCode, String description, int price) 时出现错误
编辑3:好的,我想我用这些代码行解决了这个问题。我是java新手..仍在练习和学习:) ...感谢大家的洞察力
private ItemCatalog() {
}
private ItemCatalog(String itemCode,String description, int price){
super(itemCode,description, price);
}
编辑 4:我不确定这是否正确,但想在类 item 中使用 getPrice 方法来返回 searchcatalog 的结果,这是一个价格。这会是正确的设计吗?