加入收藏 | 设为首页 | 会员中心 | 我要投稿 PHP编程网 - 黄冈站长网 (http://www.0713zz.com/)- 数据应用、建站、人体识别、智能机器人、语音技术!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

JavaScript 的一些常用设计模式

发布时间:2019-08-20 03:46:49 所属栏目:优化 来源:xianshannan
导读:副标题#e# 设计模式是前人解决某个特定场景下对而总结出来的一些解决方案。可能刚开始接触编程还没有什么经验的时候,会感觉设计模式没那么好理解,这个也很正常。有些简单的设计模式我们有时候用到,不过没意识到也是存在的。 学习设计模式,可以让我们在

例子

  1. function order(options) { 
  2.   return { 
  3.     next: (callback) => callback(options), 
  4.   } 
  5.  
  6. function order500(options) { 
  7.   const { orderType, pay } = options 
  8.   if (orderType === 1 && pay === true) { 
  9.     console.log('500 元定金预购, 得到 100 元优惠券') 
  10.     return { 
  11.       next: () => {}, 
  12.     } 
  13.   } else { 
  14.     return { 
  15.       next: (callback) => callback(options), 
  16.     } 
  17.   } 
  18.  
  19. function order200(options) { 
  20.   const { orderType, pay } = options 
  21.   if (orderType === 2 && pay === true) { 
  22.     console.log('200 元定金预购, 得到 50 元优惠券') 
  23.     return { 
  24.       next: () => {}, 
  25.     } 
  26.   } else { 
  27.     return { 
  28.       next: (callback) => callback(options), 
  29.     } 
  30.   } 
  31.  
  32. function orderCommon(options) { 
  33.   const { orderType, stock } = options 
  34.   if (orderType === 3 && stock > 0) { 
  35.     console.log('普通购买, 无优惠券') 
  36.     return {} 
  37.   } else { 
  38.     console.log('库存不够, 无法购买') 
  39.   } 
  40.  
  41. order({ 
  42.   orderType: 3, 
  43.   pay: true, 
  44.   stock: 500, 
  45. }) 
  46.   .next(order500) 
  47.   .next(order200) 
  48.   .next(orderCommon) 
  49. // 打印出 “普通购买, 无优惠券” 

上面的代码,对 order 相关的进行了解耦,order500,order200、orderCommon 等都是可以单独调用的。

(编辑:PHP编程网 - 黄冈站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读