js设计模式之工厂模式

原型链实现

let UserFactory = function (role) {
    if (this instanceof UserFactory) {
        let s = new this[role]
        return s
    } else {
        return new UserFactory(role)
    }
}
UserFactory.prototype={
    SumperAdmin:function (){
        this.name="超级管理员"
        this.viewPage=['首页','通讯页','发现页','应用数据','权限管理']
    },
    Admin:function (){
        this.name="管理员"
        this.viewPage=['首页','通讯页','发现页','应用数据']
    },
    NormalUser:function (){
        this.name="普通用户"
        this.viewPage=['首页','通讯页','发现页']
    }
}
let superAdmin=UserFactory('SumperAdmin')
console.log(superAdmin.viewPage)
let Admin=UserFactory('Admin')
console.log(Admin.viewPage)
let NormalUser=UserFactory('NormalUser')
console.log(NormalUser.viewPage)

class实现工厂模式

class Animal{
        constructor(name) {
            this.name = name;
        }
    }
    class Creator{
        create(name){
            return new Animal(name)
        }
    }
    let creator=new Creator()
    let cat=creator.create('cat')
    console.log(cat.name)
    let dog=creator.create('dog')
    console.log(dog.name)

你可能感兴趣的:(javascript,设计模式,前端,js)