日期:2014-05-20 浏览次数:20772 次
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())){ if(goods.getTypeName()==e.getKey()){ continue; } e.getValue().count -= goods.count; } } } void print(){ System.out.print("库存:"); boolean fistCycle=true; for(Map.Entry<String, Goods> e : depository.entrySet()){ if(fistCycle){ fistCycle=false; }else{ System.out.print(','); } System.out.print(e.getKey()); System.out.print(e.getValue().getCount()); } System.out.println(); } } public static void main(String[] args) { Deposite deposite = new Deposite(); deposite.add(new Goods(100)); deposite.add(new Furniture(100)); deposite.add(new Table(0)); deposite.print(); System.out.println("========我==是==分==割==线========"); Purchase purchase = new Purchase(deposite); purchase.purchase(new Table(5)); Sell sell = new Sell(deposite); sell.sell(new Table(1)); } }