本文旨在记录JavaScript中常用的设计模式代码片段,简要说明使用场景,不过于追究细节。在设计模式开篇之前,还是先要搞清楚JavaScript中关于面向对象的基础知识,可以先看看JavaScript面向对象小抄集
简单工厂又叫做静态工厂方法( Static Factory Method ),由一个工厂对象决定创建某一种产品对象类的实例。主要用来创建同一类对象
类型:创建型
适用场景:
代码片段:
//方式一:new对象
var Basketball = function(){
this.content = "篮球";
}
Basketball.prototype.getBallSize(){
console.log("直径20公分");
}
var Football = function(){
this.content = "足球";
}
Football.prototype.getBallSize(){
console.log("直径15公分");
}
//运动工厂
var SportFactory = function(name){
if (name == 'NBA') {
return new Basketball();
} else if (name == 'WorldCup') {
return new Football();
}
}
//方式二:创建一个新对象,然后包装增强属性和方法实现
function createBall(name,content){
//创建一个对象,然后扩展(这种方式又叫做寄生方式)
var o = new Object();
o.content = content;
o.getContent = function(){
return this.content;
}
//各个对象的差异部分
if (name == 'NBA') {
}
else if (name == 'WorldCup') {
}
return o;
}
原文:https://www.cnblogs.com/DiDi516/p/11762497.html