【简单工厂模式】:同种类
var cat = function () { this.hh = ‘高冷‘ } cat.prototype = { pin: function () { console.log("白色"); } } var dog = function () { this.hh = ‘粘人‘ } dog.prototype ={ pin: function () { console.log("黄色"); } } var ren = function(pet){ switch (pet){ case ‘qinjin‘: return new dog(); case ‘gaoleng‘: return new cat(); } } var guke = ren(qinjin) console.log(guke); function cat(name,pinzhong,price) { var o = new Object(); o.name = name; o.pinzhong = pinzhong o.price = price o.getName = function () { console.log(this.name); } return o; } var meiduan = cat(‘xiaoduanduan‘, ‘meiduan‘, 2000) var jiafei = cat(‘xiaofeifei‘,‘feifei‘, 9000) meiduan.getName(); jiafei.getName()
【工厂方法模式】
var Factory = function (type,content) {
if(this instanceof Factory){
var s = new this[type](content)
return s
}else{
return new Factory(type, content)
}
}
Factory.prototype = {
dog: function (content) {
this.content = content;
(function (content) {
var div = dosumnet.createElement(‘div‘);
div.innerHTML = content;
div.style.border = ‘1px solid red‘
document.getElementById(‘conta‘)
})(content)
},
lv: function (content) {
}
}
var data = [
{type:‘dog‘,content:‘我是一只狗‘},
{type:‘lv‘,content:‘我是一只狗‘}
]
for(var i = 2; i>0;i--){
Factory(s[i].type,s[i].content)
}
【抽象工厂模式】
// 抽象工厂模式 每个子类都有一个继承
var home = function (subType,superType) {
// 判断抽象工厂中是否有该对象类
if (typeof home[superType] === ‘function‘){
// 缓存类
function F() {
this.type=‘户型‘
}
// 继承父类属性和方法
F.prototype = new home[superType];
// 将自雷constructor指向子类
subType.constructor = subType
// 子类原型继承"父类"
subType.prototype = new F();
}else{
// 不存在该抽象类抛出错误
throw new Errow(‘未创建该抽象类‘)
}
}
// 别墅类
home.villa = function () {
this.type = ‘villa‘
console.log(‘car‘, this);
}
home.villa.prototype = {
getPrice: function () {
},
gethuxing: function () {
}
}
// 低档住宅
var swimvilla = function (mianji,huxing) {
this.mianji = mianji;
this.huxing = huxing;
}
// 抽象工厂实现对villa抽象类的继承
home(swimvilla, ‘villa‘);
swimvilla.prototype.getPrice = function () {
console.log(this.price)
}
swimvilla.prototype.gethuxing = function () {
console.log(this.huxing);
}
const swimvilla1 = new swimvill(100,‘5室‘)
swimvilla1.getPrice()