/*
工厂方法模式:通过对产品类的抽象使其创建业务主要负责用于创建多类产品的实例
*/
/*
安全工厂方法就是在构造函数中进行判断,当构造函数被引用时判断构造函数的this的实例是否是这个构造函数,
如果不是那么就将实例化好的函数return 出去;
我们知道在js中可以自定义对象,
我们可以通过instanceof这个方法定义来监测,这个实例是哪一个对象的;
函数数组都可以称之为对象
*/
var Demo = function (text) {
if (!(this instanceof Demo)) {
return new Demo(text)
}
this.text = text;
}
Demo.prototype.show = function () {
console.log(this.text)
}
var d = Demo("爱上了快递费即可")
d.show()
/* 例子:*/
//需求广告资源投放,关于计算机培训的,一批java,用绿色字体,还有一批php,用黄色字体红色背景
//创建Java类
var Java = function (text) {
this.text = text;
(function (text) {
var div = document.createElement("div")
div.innerHTML = text;
div.style.color = "yellow";
document.getElementById("java").appendChild(div)
})(this.text)
}
//创建Php类
var Php = function (text) {
this.text = text;
(function (text) {
var div = document.createElement("div");
div.innerHTML = text;
div.style.color = "red";
document.getElementById("php").appendChild(div)
})(this.text)
}
//简单工厂方法,每次修改需要修改俩次,一个是构造函数,一个是工厂函数
/* var Factory=function(type,text){
switch(type){
case 'java':
return new Java(text);
break;
case 'php':
return new Php(text);
break;
}
}
Factory("php","java学科"); */
//工厂方法模式本意是说将实际创建对象的工作推迟到子类当中
//简单的工厂方法是将类放在一个构造函数中,然后在工厂函数内部通过判断,将类return回去,
//工厂方法是将构造函数写在工厂函数的原型上,
var Factory = function (type, text) {
// console.log(type,text)
// return false;
//判断当前这个方法的this是否指向了当前方法的实例
if (this instanceof Factory) {
console.log(this)
var s = new this[type](text);
return s;
} else {
return new Factory(type, text)
}
}
Factory.prototype = {
java: function (text) {
(function (text) {
var div = document.createElement("div")
div.innerHTML = text;
div.style.color = "yellow";
document.getElementById("java").appendChild(div)
})(text)
},
php: function (text) {
(function (text) {
var div = document.createElement("div");
div.innerHTML = text;
div.style.color = "red";
document.getElementById("php").appendChild(div)
})(text)
}
}
Factory("php", "php学科")