js设计模式问题

export const typeMarry = (type) => {
  const charts = ['pie','bar','line'],
        text = ['normalText','multText'],
        media = ['file','picture','music','video']
  if(charts.indexOf(type) !== -1) {
    return 'CHARTS'
  }
  if(text.indexOf(type) !== -1) {
    return 'TEXT'
  }
  if(media.indexOf(type) !== -1) {
    return 'MEDIA'
  }
}

这个方法如何改写成维护性高写法,类似于策略模式?

阅读 2.3k
3 个回答

扩展的话只用修改types就行了

const types = {
  'CHARTS':['pie','bar','line'],
  'TEXT':['normalText','multText'],
  'MEDIA':['file','picture','music','video'],
}

export const typeMarry = (type) => {
   for(var k in types)
     if(types[k].includes(type))
       return k;
}
function isCharts (type) {
  return ['pie','bar','line'].includes(type) ? 'CHARTS' : false
}

function isText (type) {
  return ['normalText','multText'].includes(type) ? 'TEXT' : false
}

function isMedia (type) {
  return ['file','picture','music','video'].includes(type) ? 'MEDIA' : false
}

const typefun = [isCharts, isText, isMedia]

export const typeMarry = (type) => {
  for (let i = 0, len = typefun.length; i < len; i++) {
    let cur = typefun[i](type)
    if (cur) return cur
  }
}

直接返回组件实例就行了,没有更多代码的话也没什么好优化的点。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题