📄 cart.java
字号:
package jdbcbook.shopping.bean;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import jdbcbook.shopping.form.Product;
import jdbcbook.shopping.database.OperateDB;
public class Cart
{
public Cart()
{
this.cartitems = new ArrayList();
this.totalfee = new BigDecimal( 0 );
}
// 记录购物车中的总费用
private BigDecimal totalfee;
public BigDecimal getTotalfee( )
{
return this.totalfee;
}
public void setTotalfee( BigDecimal totalfee )
{
this.totalfee = totalfee;
}
// 记录购物车中的每一个商品信息
private Collection cartitems;
public Collection getCartitems( )
{
return this.cartitems;
}
public void setCartitems( Collection cartitems )
{
this.cartitems = cartitems;
}
// 向购物车中增加商品
public synchronized void addCartitem( int productid, int quantity )
{
if( productid<=0 || quantity<=0 ) return;
Product product = (Product)OperateDB.getObjectByID( Product.class, productid );
if( product!=null )
addCartitem( product, quantity );
}
// 向购物车中增加商品
public synchronized void addCartitem( Product product, int quantity )
{
if( product==null || quantity<=0 ) return;
// 判断是否已经存在
Iterator it = this.cartitems.iterator();
while( it.hasNext() )
{
CartItem ci = (CartItem)it.next();
Product p = ci.getProduct();
if( product.getId() == p.getId() )
return;
}
// 生成购物车条目
CartItem cartitem = new CartItem();
cartitem.setProduct( product );
cartitem.setQuantity( quantity );
cartitem.setTotalfee( product.getPrice().multiply( new BigDecimal( quantity ) ) );
((ArrayList)cartitems).add( cartitem );
// 计算总费用
setTotalfee( getTotalfee().add( cartitem.getTotalfee() ) );
}
// 从购物车中删除商品
public synchronized void delCartitem( int productid )
{
if( productid <=0 ) return;
Iterator it = this.cartitems.iterator();
while( it.hasNext() )
{
CartItem cartitem = (CartItem)it.next();
Product product = cartitem.getProduct();
if( product.getId()==productid )
{
double totalfee = getTotalfee().doubleValue() - cartitem.getTotalfee().doubleValue();
setTotalfee( new BigDecimal( totalfee ) );
it.remove();
}
}
}
// 修改购物车中商品的数量
public synchronized void updateCartitem( int productid, int quantity )
{
delCartitem( productid );
addCartitem( productid, quantity );
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -