Java第一次任务:购物车程序的面向对象设计
-
0.人员分工
![]()
-
1.前期调查
从京东商城中体验购物车功能
进入商城,展示商品列表
![]()
添加商品,进入购物车
![]()
-
2.系统功能结构图
![]()
![]()
![]()
-
3.系统描述
用户进入商城,展示商品清单:- 选中商品,加入购物车;
- 进入购物车,展示购物车中商品;
- 选中商品,从购物车中删除;
- 清空购物车
-
4.类功能说明
![]()
![]()
![]()
![]()
-
5.封装性、继承体现
`class Product{
private String name;
private int id;
private static int count;
private int num;
private double price;
public Product() {
}
public Product(String name, int num, double price) {
this.name = name;
this.num = num;
this.price = price;
if(ShoppingCart.map.get(name)==null)count++;
id = count;
}
@Override
public String toString() {
return "Products{" +
"name='" + name + '\'' +
", num=" + num +
", price=" + price +
",id="+id+
'}';
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Product setName(String name) {
this.name = name;
return this;
}
public int getNum() {
return num;
}
public Product setNum(int num) {
this.num = num;
return this;
}
public double getPrice() {
return price;
}
public Product setPrice(double price) {
this.price = price;
return this;
}
}
`
商品的数量、名称等属性都是私有的,只能setter、getter方法获取和修改,体现了面向对象的封装性
`class ShoppingCart{
/*
属性:商品列表
方法:加入、删除、增添商品数目、清空商品数目、计算商品总额、展示商品列表
* */
LinkedList<Product> products= new LinkedList<>();
static HashMap<String,Integer> map = new HashMap<>();//判断商品是否存在
public void showProducts(){//展示商品列表
for (Product item:products) {
System.out.println(item.toString());
}
}
public void addProduct(Product item){//添加商品
if(map.get(item.getName()) != null){//如果购物车中已存在该商品,仅增添数量
for (Product e : products) {
if(e.getName().equals(item.getName())){
e.setNum(e.getNum()+item.getNum());
break;
}
}
}
else {//未存在该商品,则将商品加入列表,并建立映射
products.add(item);
map.put(item.getName(), item.getId());
}
}
public void delProduct(Product item){//删除列表中的商品
map.remove(item.getName());
products.remove(item.getName());
}
public void clearProduct(){//清空购物车
products.clear();
}
public double sumProduct(){
double sum = 0;
for (Product e : products) {
sum = sum + e.getNum() * e.getPrice();
}
return sum;
}
}
-
6. 项目包结构
目前只实现了shopping包,这个包中主要向用户提供购物车对商品的一系列操作,在后续代码的完善中考虑添加consumer包和admi包,实现顾客和管理员对商品的不同操作。 -
7.代码管理
为了更好地实现对代码的管理,使用gitee
将初步完成的代码导入码云中:
![]()
![]()












浙公网安备 33010602011771号