⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shoppingcartserviceimpl.java

📁 一个经典购物车(shoppingcart)实例代码
💻 JAVA
字号:
package com.jpioneer.application.shoppingcart.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.jpioneer.application.shoppingcart.domain.ShoppingCartItem;
import com.jpioneer.application.shoppingcart.service.ShoppingCartService;

public class ShoppingCartServiceImpl implements ShoppingCartService{
	protected Map items = new HashMap();
	//添加
	public void addItem(String id, String name, double price, double quantity)
		throws Exception {
		if (items.containsKey(id)) //存在的话数量相加
			{
			ShoppingCartItem tempSC = (ShoppingCartItem) items.get(id);
			//取出已经存在的这个商品
			tempSC.setQuantity(quantity + tempSC.getQuantity());
		} else {
			ShoppingCartItem sc = new ShoppingCartItem();
			sc.setId(id);
			sc.setName(name);
			sc.setPrice(price);
			sc.setQuantity(quantity);

			items.put(id, sc); //存在到哈稀中,模拟一个购物车
		}
	}
	//更新
	public void editCart(String id,double quantity) throws Exception {
		ShoppingCartItem tempSC = (ShoppingCartItem) items.get(id);
		tempSC.setQuantity(quantity);		
	}
	//删除
	public void delCart(String id) throws Exception {
		items.remove(id);
	}
	//获取所有
	public List getAllCarts() throws Exception {
		ShoppingCartItem sc = null;
		List list=new ArrayList();
		Iterator it = items.keySet().iterator();
		while (it.hasNext()) {
			String key = (String)it.next();
			sc=(ShoppingCartItem)items.get(key);
			list.add(sc);
		}
	    return list;
	}
	//获取总数量 
	public float getTotalQuantity() throws Exception {
		ShoppingCartItem sc = null;
		Iterator it = items.keySet().iterator();
		float totalQuantity = 0;
		while (it.hasNext()) {
			String key = (String)it.next();
			sc=(ShoppingCartItem)items.get(key);
			totalQuantity += sc.getQuantity();
		}
		return totalQuantity;
	}
	//获取总金额
	public float getTotalPrice() throws Exception {
		ShoppingCartItem sc = null;
		Iterator it = items.keySet().iterator();
		float totalPrice = 0;
		while (it.hasNext()) {
			String key = (String)it.next();
			sc=(ShoppingCartItem)items.get(key);
			totalPrice += sc.getPrice() * sc.getQuantity();
		}
		return totalPrice;
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -