一个超市类SuperMaket作为主类,一个抽象商品类Goods,一个抽象家具类Furniture,一个具体桌子Table类。进货类Purchase,销售类Sell,库存类Deposite。要求商品进货时库存中商品自动增加,商品销售时库存商品自动减少;货物原有200,其中家具100,桌子0。
输出:
进货: 桌子5
库存:桌子5,家具105,货物205
销售: 桌子1
库存:桌子4,家具104,货物204
要求:因为类似于桌子的商品成千上万,为了代码复用、具有普遍性,Purchase,Sell,Deposite三个类中不允许带有Table、Furniture名称或带有“桌子”“家具”字符串的语句,如果有,不给分。但可以带有Goods名称或“货物”字符串,因其具有通用性。Table类中可以带有“家具”字符串的语句,因为它是家具类的子类,具有通用性。
------解决方案--------------------
太2了。
谁能发明这么不切实际的题目啊~~.
真纠结
import java.util.HashMap;
import java.util.Map;
public class SuperMaket {
public interface TypeAware{
String getTypeName();
int getCount();
}
public static class Goods implements TypeAware{
private final static String TypeName="货物";
int count;
public Goods(int count) {
this.count = count;
}
public String getTypeName() {
return TypeName;
}
public int getCount() {
return count;
}
}
public static class Furniture extends Goods{
private final static String TypeName="家具";
public Furniture(int count) {
super(count);
}
public String getTypeName() {
return TypeName;
}
}
public static class Table extends Furniture{
private final static String TypeName= "桌子";
public Table(int count) {
super(count);
}
public String getTypeName() {
return TypeName;
}
}
public static class Purchase{
private Deposite deposite;
public Purchase(Deposite deposite) {
this.deposite = deposite;
}
void purchase(Goods goods){
deposite.add(goods);
print(goods);
}
void print(Goods goods){
System.out.println("进货:"+goods.getTypeName()+goods.getCount());
deposite.print();
}
}
public static class Sell{
private Deposite deposite;
public Sell(Deposite deposite) {
this.deposite = deposite;
}
void sell(Goods goods){
deposite.remove(goods);
print(goods);
}
void print(Goods goods){
System.out.println("销售:"+goods.getTypeName()+goods.getCount());
deposite.print();
}
}
public static class Deposite{
Map<String, Goods> depository = new HashMap<String, Goods>();
void add(Goods goods){
Goods g = depository.get(goods.getTypeName());
if(g==null){
depository.put(goods.getTypeName(), goods);
}else{
g.count += goods.count;
}
for(Map.Entry<String, Goods> e : depository.entrySet()){
if(e.getValue().getClass().isAssignableFrom(goods.getClass())){
if(goods.getTypeName()==e.getKey()){
continue;
}
e.getValue().count += goods.count;
}
}
}
void remove(Goods goods){
Goods g = depository.get(goods.getTypeName());
if(g!=null){
g.count -= goods.count;
}
for(Map.Entry<String, Goods> e : depository.entrySet()){
if(e.getValue().getClass().isAssignableFrom(goods.getClass())){