灏天阁

策略模式

· Yin灏
/**
 * 策略模式
 */

// 价格策略对象
var PriceStrategy = function () {
  // 内部算法对象
  var stragtegy = {
    // 100 返 30
    return30: function (price) {
      // +price: 转化为数字类型
      return +price + parseInt(price / 100) * 30;
    },
    // 100 返 50
    return50: function (price) {
      // +price: 转化为数字类型
      return +price + parseInt(price / 100) * 50;
    },
    // 9 折
    percent90: function (price) {
      // 在 JS 在处理小数乘法有 bug,故运算前转化为整数
      return (price * 100 * 90) / 10000;
    },
    // 8 折
    percent80: function (price) {
      return (price * 100 * 80) / 10000;
    },
    // 5 折
    percent50: function (price) {
      return (price * 100 * 50) / 10000;
    },
  };
  return function (algorithm, price) {
    return stragtegy[algorithm] && stragtegy[algorithm](price);
  };
};

// 测试用例
var price = PriceStrategy("return50", "314.67");
console.log(price); // 464.67

/**
 * 表单验证
 */
var InputStrategy = function () {
  var stragtegy = {
    // 是否为空
    notNull: function (value) {
      return /\s+/.test(value) ? "请输入内容" : "";
    },
    // 是否是一个数字
    number: function (value) {
      return /^[0-9]+(\.[0-9]+)?$/.test(value) ? "" : "请输入数字";
    },
    // 是否是本地电话
    phone: function (value) {
      return /^\d{3}\-\d{8}$|^\d{4}\-\d{7}$/.test(value)
        ? ""
        : "请输入正确的电话号码格式, 如: 010-12345678 或 0418-1234567";
    },
  };
  return {
    check: function (type, value) {
      value = value.replace(/^\s+|\s+$/g, "");
      return stragtegy[type] ? stragtegy[type](value) : "没有类型的检测方法";
    },
    // 添加策略
    addStragtegy: function (type, fn) {
      stragtegy[type] = fn;
    },
  };
};

InputStrategy.addStragtegy("nickname", function (value) {
  return /^[a-zA-Z]\w{3, 7}$/.test(value) ? "" : "请输入 4-8 位昵称, 如: YYQH";
});

// 调用
function $tag(tag, context) {
  context = context || document;
  return context.getElementsByTagName(tag);
}

$tag("click")[1].onclick = function () {
  var value = $tag("input")[0].value;
  $tag("span")[0].innerHTML = InputStrategy.check("nickname", value);
};

- Book Lists -