zoukankan      html  css  js  c++  java
  • JavaScript 工厂模式

      //工厂
      function FruitMaker() {
         //function 后不带方法名,这里cococola未定义,make return时,返回 FruitMaker.cococola
        this.cococola = function cococola (price) {
          console.log("生成一瓶Coca-Cola,多少钱:" + price);
        }
    
        this.xuebi = function xuebi(price) {
          console.log("生成一瓶可乐,多少钱:" + price);
        }
      }
    
      //生产线
      FruitMaker.prototype.make = function (water, price) {
        try {
          var func = this[water];
          func.prototype = FruitMaker.prototype;
          return new func(price);
        } catch (error) {
          console.log("很抱歉, 公司暂时不能生产" + water + "这种果汁, ....");
        }
      }
    
      var maker = new FruitMaker();
      var cocoCola = maker.make("cococola", "3.1");
      console.log(cocoCola);
      var xuebi = maker.make("xuebi", "3.2");
      console.log(xuebi);
    
      var fenda = maker.make("fenda", "3.3");
      console.log(fenda);
    

    如果需要开发新产品(这里 ->芬达)

      //生产线(新开发产品)
      FruitMaker.prototype.extend = function (obj) {
        for (var key in obj) {
          this[key] = obj[key];
        }
      };
    
    

    调用的时候:

      maker.extend({
        "fenda": function coco(price) {
          console.log("生成一瓶fenda,多少钱:" + price);
        }
      });
    
      var fenda = maker.make("fenda", "3.3");
      console.log(fenda);
    

  • 相关阅读:
    Chrome即将封杀Google Earth、Google Talk等插件
    诗情画意
    奇联妙对
    理解大型分布式网站你必须知道这些概念 (转)
    RESTful API
    什么是微服务?
    Spring Cloud与Spring Boot的关系
    springboot定时任务
    SpringBoot工程目录配置
    Spring Boot中配置文件application.properties使用
  • 原文地址:https://www.cnblogs.com/tangge/p/11909265.html
Copyright © 2011-2022 走看看