通过模版类把公共内容进行抽离封装、提供给其他子类继承使用

主要解决:一些方法通用,却在每一个子类都重新写了这一方法。
何时使用:有一些通用的方法。
如何解决:将这些通用算法抽象出来。
关键代码:在抽象类实现,其他步骤在子类实现。
应用实例:
1、在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。
2、西游记里面菩萨定好的 81 难,这就是一个顶层的逻辑骨架。

提示框案例

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. </body>
  11. </html>
  12. <script>
  13. class Alert{
  14. constructor(data){
  15. const { content, close, confirm, success, fail } = data;
  16. this.content = content;
  17. // 提示框面板
  18. this.panel = document.createElement('div')
  19. // 提示内容组件
  20. this.contentNode = document.createElement('p')
  21. this.contentNode.innerHTML = content;
  22. // 创建确认按钮组件
  23. this.confirmBtn = document.createElement('span')
  24. this.confirmBtn.innerHTML = confirm || '确认'
  25. // 创建关闭按钮组件
  26. this.closeBtn = document.createElement('b')
  27. this.closeBtn.innerHTML = close || '关闭'
  28. // 事件绑定
  29. this.success = success || function(){}
  30. this.fail = fail || function(){}
  31. }
  32. init(){
  33. this.panel.appendChild(this.contentNode)
  34. this.panel.appendChild(this.confirmBtn)
  35. this.panel.appendChild(this.closeBtn)
  36. document.body.appendChild(this.panel)
  37. this.bindEvent()
  38. }
  39. bindEvent(){
  40. this.confirmBtn.onclick = () =>{
  41. this.success()
  42. this.hide()
  43. }
  44. this.closeBtn.onclick = () =>{
  45. this.fail()
  46. this.hide()
  47. }
  48. }
  49. hide(){
  50. this.panel.style.display = 'none'
  51. }
  52. show(){
  53. this.panel.style.display = 'block'
  54. }
  55. }
  56. class MessageBox extends Alert{
  57. constructor({ confirm }){
  58. super({
  59. content:"您是否需要执行删除操作??",
  60. confirm:"确认",
  61. close:"取消",
  62. success:confirm,
  63. })
  64. }
  65. }
  66. function confirms(){
  67. console.log('用户按了确认')
  68. }
  69. let messageBox = new MessageBox({
  70. confirm:confirms
  71. })
  72. messageBox.init()
  73. </script>

总结

优点

  • 公共的抽离、扩展性好