美文网首页
设计模式----简单工厂模式

设计模式----简单工厂模式

作者: 简爱_cdde | 来源:发表于2018-12-11 19:15 被阅读0次

     简单工厂模式:又叫静态工厂方法,由一个工厂对象决定创建某一种产品对象类实例;主要用来创建同一类对象!

            function createBook(name, time, type) {

                var o = new Object();

                o.name = name;

                o.time = time;

                o.type = type;

                o.getName = function () {

                    console.log(this.name)

                }

                return o;

            }

            /*


            只有通过new 创建的对象才能使用私有的属性

            和方法


            */

            var loginAlert = new LoginAlert("密码输入有误!")

            loginAlert.show();

            /* constructor是一个属性:当创建一个函数或者对象时都会为其创建一个原型对象prototype,

            在prototype对象中又会像函数中创建this一样创建一个constructor属性,

            那么constructor属性指向的就是拥有整个原型对象的函数或者是对象, */

            /*


            例子


            */

            //弹框

            function LoginAlert(text) {

                this.text = text;

            }

            LoginAlert.prototype.show = function () {

                console.log((this.text))

            }

            //输入弹框

            function LoginPromt(text) {

                this.text = text;

            }

            LoginPromt.prototype.show = function () {

                console.log((this.text))

            }

            //确认弹框

            function LoginConfirm(text) {

                this.text = text;

            }

            LoginConfirm.prototype.show = function () {

                console.log((this.text))

            }

            /*

            定义的类太多容易在团队合作中出现变量名重复的问题,

          而且类太多不容易记住,我们改造的方法是定义一个大类,这个大类就是一个大的工厂,

          当我们需要什么产品的时候,只要将产品名称传进去,就会相应的启动那条产品线,

          简单工厂就是返回一个对象

            */

            var Factory = function (type, text) {

                switch (type) {

                    case 'alert':

                        return new LoginAlert(text);

                        break;

                    case 'promt':

                        return new LoginPromt(text);

                        break;

                    case 'confirm':

                        return new LoginConfirm(text);

                        break;

                }

            }

    相关文章

      网友评论

          本文标题:设计模式----简单工厂模式

          本文链接:https://www.haomeiwen.com/subject/ydlxtqtx.html