jQuery 版本购物车(融入设计模式)
1. 介绍
1.1 功能
- 显示购物列表、加入购物车、从购物车删除
1.2 用到的设计模式
- 工厂模式
$('XXX')
,创建商品
- 单例模式
- 购物车
- 装饰器模式
- 打点统计
- 观察者模式
- 网页事件、Promise
- 状态模式
- 添加/删除购物车
- 模板方法模式
init()
,统一的方法渲染
- 代理模式
- 打折商品信息处理
1.3 UML 演示
2. 代码演示
2.1 代码目录
2.2 api
- list.json
[ { id: 1, name: '《JS高级程序设计》', price: 87, discount: 1 }, { id: 2, name: '《新零售》', price: 42, discount: 1 }, { id: 3, name: '《干法》', price: 56, discount: 0 }, { id: 4, name: '《剑指offer》', price: 32, discount: 0 } ]
2.3 config
- config.js
export const GET_LIST = '../api/list.json'
2.4 List
-
CreateItem.js
import Item from './Item.js' //优惠商品处理逻辑 function createDiscount(itemData) { //代理模式 return new Proxy(itemData, { get: function(target, key, receicer) { if (key === 'name') { return `${ target[key]}【折扣】` } if (key === 'price') { return Math.floor(target[key] * 0.8 * 100) / 100 } return target[key] } }) } //工厂模式 export default function(list, itemData) { if (itemData.discount) { itemData = createDiscount(itemData) } return new Item(list, itemData) }
-
Item.js
import $ from 'jquery' import getCart from '../ShoppingCart/GetCart.js' import StateMachine from 'javascript-state-machine' import { log } from '../util/log' export default class Item { constructor(list, data) { this.list = list this.data = data this.$el = $('<div>') this.cart = getCart