加入收藏 | 设为首页 | 会员中心 | 我要投稿 威海站长网 (https://www.0631zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

JavaScript 的一些常用设计模式

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

例子

  1. class A { 
  2.   getContent() { 
  3.     return '第一行内容' 
  4.   } 
  5.   render() { 
  6.     document.body.innerHTML = this.getContent() 
  7.   } 
  8.  
  9. function decoratorOne(cla) { 
  10.   const prevGetContent = cla.prototype.getContent 
  11.   cla.prototype.getContent = function() { 
  12.     return ` 
  13.       第一行之前的内容 
  14.       <br/> 
  15.       ${prevGetContent()} 
  16.     ` 
  17.   } 
  18.   return cla 
  19.  
  20. function decoratorTwo(cla) { 
  21.   const prevGetContent = cla.prototype.getContent 
  22.   cla.prototype.getContent = function() { 
  23.     return ` 
  24.       ${prevGetContent()} 
  25.       <br/> 
  26.       第二行内容 
  27.     ` 
  28.   } 
  29.   return cla 
  30.  
  31. const B = decoratorOne(A) 
  32. const C = decoratorTwo(B) 
  33. new C().render() 

策略模式

在策略模式(Strategy Pattern)中,一个行为或其算法可以在运行时更改。

(编辑:威海站长网)

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

热点阅读