灏天阁

简单工厂模式

· Yin灏
// 篮球基类
var Basketball = function () {
  this.intro = "篮球盛行于美国";
};
Basketball.prototype = {
  getMember: function () {
    console.log("每个队伍需要5名队员");
  },
  getBallSize: function () {
    console.log("篮球很大");
  },
};

// 足球基类
var Football = function () {
  this.intro = "足球在世界范围内很流行";
};
Football.prototype = {
  getMember: function () {
    console.log("每个队伍需要11名队员");
  },
  getBallSize: function () {
    console.log("足球很大");
  },
};

// 网球基类
var Tennis = function () {
  this.intro = "每年有很多的网球系列赛";
};
Tennis.prototype = {
  getMember: function () {
    console.log("每个队伍需要1名队员");
  },
  getBallSize: function () {
    console.log("网球很小");
  },
};

// 运动工厂
var SportsFactory = function (name) {
  switch (name) {
    case "NBA":
      return new Basketball();
    case "wordCup":
      return new Football();
    case "FrenchOpen":
      return new Tennis();
  }
};

// 使用
var footnall = SportsFactory("wordCup");
console.log(footnall);
console.log(footnall.intro);
footnall.getMember();

/**
 * 一个对象有时也可以代替许多类
 */
// 工厂模式
function createBook(name, time, type) {
  // 创建一个对象,并对对象拓展属性和方法
  var o = new Object();
  o.name = name;
  o.time = time;
  o.type = type;
  o.getName = function () {
    console.log(this.name);
  };
  // 将对象返回
  return o;
}
var book1 = createBook("js book", 2014, "js");
var book2 = createBook("css book", 2013, "css");

book1.getName();
book2.getName();

/**
 * 应用
 */
function createPop(type, text) {
  // 创建一个对象,并对对象拓展属性和方法
  var o = new Object();
  o.content = text;
  o.show = function () {
    // 显示方法
  };
  if (type == "alert") {
    // 警示框差异部分
  }
  if (type == "prompt") {
    // 提示框差异部分
  }
  if (type == "confirm") {
    // 确认框差异部分
  }
  // 将对象返回
  return o;
}

// 创建警示框
var userNameAlert = createPop("alert", "用户名只能是 26个字母和数字");

- Book Lists -