综合实战:超市购物车
使用面向对象的概念表示出下面的生活场景:巧明去超市买东西,所有买到的东西都放在了购物车之中,最后到收银台一起结账。
1、定义出一个商品的标准:
interface IGoods{
//定义商品标准
public String getNmae();
public double getPrice();
}
2、定义购物车处理标准
interface IShopCar{
//购物车
public void add(IGoods goods);//添加商品信息
public void delete(IGoods goods);//删除商品
public Object getAll();//获得购物车中的全部商品信息
}
3、定义购物车的一个实现类
class ShopCarImpl implements IShopCar{
//购物车
private ILink<IGoods> allGoodses = new ILinkImpl<IGoods>();
public void add(IGoods goods) {
this.allGoodses.add(goods);
}
public void delete(IGoods goods) {
this.allGoodses.remove(goods);
}
public Object [] getAll() {
return this.allGoodses.toArray();
}
}
4、定义收银台
class Cashier{
//收银台
private IShopCar shopCar;
public Cashier(IShopCar shopCar) {
this.shopCar = shopCar;
}
public double allPrice() {
//计算总价
double all = 0.0;
Object result [] = this.shopCar.getAll();
for(Object obj : result) {
IGoods goods = (IGoods) obj;
all += goods.getPrice();
}
return all;
}
public int allCount() {
//商品数量
return this.shopCar.getAll().length;
}
}
5、定义商品信息:
图书:
class Book implements IGoods{
private String name;
private double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return this.name;
}
public double getPrice() {
return this.price;
}
public boolean equals(Object obj) {
if(obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (!(obj instanceof Book)) {
return false;
}
Book book = (Book) obj;
return this.name.equals(book.name) && this.price == book.price;
}
public String toString() {
return "【图书信息】名称:" + this.name + "、价格:" + this.price;
}
}
书包:
class Bag implements IGoods{
private String name;
private double price;
public Bag (String name, double price) {
this.name = name;