策略模式

57 阅读1分钟

Go

// 策略接口
type IStrategy interface {
    DoOperate(param1 int, param2 int) int
}

// 不同策略
type Add struct{}

func (c *Add) DoOperate(param1 int, param2 int) int {
    return param1 + param2
}

type Subtract struct{}

func (c *Subtract) DoOperate(param1 int, param2 int) int {
    return param1 - param2
}

type Context struct {
    strategy IStrategy
}

func NewContext(strategy IStrategy) *Context {
    return &Context{
        strategy: strategy,
    }
}

func main() {
    var result int
    var ctx = NewContext(&Add{})
    result = ctx.strategy.DoOperate(1, 3)
    fmt.Println(result)
    ctx = NewContext(&Subtract{})
    result = ctx.strategy.DoOperate(1, 3)
    fmt.Println(result)
}

JS

//  各种策略
var strategies = {
  isPhone: function(val, errMsg) {
    if (!/(^1[3|5|7|8][0-9]{9}$)/.test(val)) {
      return errMsg;
    }
  },

  isNumber: function(val, errMsg) {
    if (typeof val !== 'number') {
      return errMsg
    }
  }
}

// 验证
class Validator {

  constructor() {
    this.cache = []
  }
  add(rule, value, errMsg) {
    this.cache.push(strategies[rule].bind({}, value, errMsg))
  }
  check() {
    for (let i in this.cache) {
      if (this.cache[i]()) {
        return this.cache[i]()
      }
    }
  }
}


function main() {
  const validator = new Validator()
  validator.add('isPhone', 13236566666, '请输入正确的手机号')
  validator.add('isNumber', 11, '请输入数字')
  if (validator.check()) {
    console.log(validator.check())
  } else {
    console.log('无错误')
  }
}

TS

// 策略接口
interface IStrategy {
  validator(): string
}

class IsPhone implements IStrategy {
  constructor(public value: string, public errMsg: string) {
    this.value = value
    this.errMsg = errMsg
  }
  validator(): string {
    if (!/(^1[3|5|7|8][0-9]{9}$)/.test(this.value)) {
      return this.errMsg;
    }
    return ''
  }
}

class IsNumber implements IStrategy {
  constructor(public value: number, public errMsg: string) {
    this.value = value
    this.errMsg = errMsg
  }
  validator(): string {
    if (typeof this.value !== 'number') {
      return this.errMsg
    }
    return ''
  }
}


class Validator {
  private cache: IStrategy[]
  constructor() {
    this.cache = []
  }

  add(strategy: IStrategy) {
    this.cache.push(strategy)
  }
  check(): string {
    for (let i in this.cache) {
      if (this.cache[i].validator()) {
        return this.cache[i].validator()
      }
    }
    return ''
  }
}

function main() {
  const validator = new Validator()
  validator.add(new IsPhone('13236577769', '请输入正确的手机号'))
  validator.add(new IsNumber(123, '请输入数字'))
  if (validator.check()) {
    console.log(validator.check())
  } else {
    console.log('无错误')
  }
}