zoukankan      html  css  js  c++  java
  • javascript 设计模式

    1.工厂模式解释

    工厂模式定义一个用于创建对象的接口,这个接口集成多个子类的接口,可以选择性的构建对应的子类实例

    2.应用场景举例

    对象的构建十分复杂
    需要依赖具体环境创建不同实例
    处理大量具有相同属性的小对象

    3.代码解释

    子类实现

    var page = page || {};
    page.dom = page.dom || {};
    //子函数1:处理文本
    page.dom.Text = function () {
      this.insert = function (where) {
        var txt = document.createTextNode(this.url);
        where.appendChild(txt);
      };
    };
    
    //子函数2:处理链接
    page.dom.Link = function () {
      this.insert = function (where) {
        var link = document.createElement('a');
        link.href = this.url;
        link.appendChild(document.createTextNode(this.url));
        where.appendChild(link);
      };
    };
    
    //子函数3:处理图片
    page.dom.Image = function () {
      this.insert = function (where) {
        var im = document.createElement('img');
        im.src = this.url;
        where.appendChild(im);
      };
    };

    工厂处理函数实现

    page.dom.factory = function (type) {
        return new page.dom[type];
    }

    使用

    var o = page.dom.factory('Link');
    o.url = 'http://www.cnblogs.com';
    o.insert(document.body);

    工厂模式其实将多个类似的构造函数集合成一个接口,通过该接口传递需要构造的实例的类型来选择想要构造的实例。

    end !!!

  • 相关阅读:
    201006120100630
    2010080120100901
    20101120至20101220
    201155学习总结
    PublishReport.rss
    windowservice创建及部署
    提示要角色管理工具安装Microsoft .NET Framework 3.5
    部署SSIS包
    ETL及SSIS
    IbatisNet
  • 原文地址:https://www.cnblogs.com/lyjfight/p/13921129.html
Copyright © 2011-2022 走看看