简单工厂模式:创建单一对象
又叫静态工厂方法,由一个工厂对象觉得创建某一种产品对象类的实例。主要用来创建同一类对象。
需求1:提示用户,‘用户名不能多于16个字母或数字’
const LoginAlert = function (text) {
this.content = text
}
LoginAlert.prototype.show = function(){
//显示警示框
console.log('显示警示框:',this.content)
}
const userNameAlert = new LoginAlert('用户名不能多于16个字母或数字')
userNameAlert.show()
需求2:用户输入的密码不正确时,提示用户‘输入的密码不正确’
const passwordAlert = new LoginAlert('输入的密码不正确')
passwordAlert.show()
需求3:提示用户名不存在,并在警示框显示一个注册按钮
const loginConfirm = function(text){
this.content = text
}
loginConfirm.prototype.show = function(){
//显示有注册按钮的警示框
console.log('显示有注册按钮的警示框:',this.content)
}
const loginFailCongirm = new loginConfirm('您的用户名不存在,请重新输入')
loginFailCongirm.show()
需求4:登陆成功后,显示一个自定义提示框,有确定取消按钮,有欢迎语
const loginPrompt = function(){
this.content = text
}
loginPrompt.prototype.show = function(){
//显示有欢迎语的提示框
console.log('显示有欢迎语的提示框:',this.content)
}
问题所在:当把这些功能类提供给其它人使用时,每次都需要找到对应的类,比较麻烦
优化方法:应用简单工厂模式,将这些类封装到一个函数里面,使用者只需要知道这个函数,和函数需要传递的参数即可,不需要知道所有的类
优化1:简单工厂模式
const PopFactory = function(name){
switch(name){
case 'alert':return new LoginAlert()
case 'confirm':return new loginConfirm()
case 'prompt':return new loginPrompt()
}
}
问题所在:LoginAlert,loginConfirm,loginPrompt这三个类很多地方是相同的,可以抽象提出出来供应
优化方法:使用简单工厂模式实现这几个类
优化2:工厂模式
function createPop(type,text){
//创建一个对象,并对对象扩展属性和方法
const o = new Object()
o.content = text
o.show = function(){
//显示方法
}
switch(type){
case 'alert':
// 警示框差异部分
black
case 'prompt':
// 警示框差异部分
black
case 'confirm':
// 确认框差异部分
black
}
//将对象返回
return o
}
// 创建警示框
const userNameAlert2 = createPop('alert','用户名不能多于16个字母或数字')
网友评论