工厂模式一之简单工厂
工厂用来生产商品,然后卖给供应商,再由供应商转手给门店,再卖给顾客 。这样的一种生产到供应的过程,看看如何应用到我们的程序中。
1.下面以衣服店为例子。
第一步:创建衣服店类。
clothes.js
//创建一个衣服店模型。 var ClothesShop = function (){} ClothesShop.prototype = {sellClothes: function (color){var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray'];var clothes;for(var i = 0, len = clothesType.length; i < len; i++) {if(color === clothesType[i]){clothes = eval('new '+ color); //new Red(); }}//判断制造的是不是衣服。 Interface.ensureImplements(clothes, Clothes);//出售return clothes;} } /*门店1 var clothesShop1 = new ClothesShop(); */
创建一个门店模型。按照这个模型来实例化门店对象,可以创建多个门店clothesShop1,clothesShop2, clothesShop3..每个门店都有各种漂亮颜色红蓝黄绿灰的衣服。顾客通过type决定要买什么样的衣服。假设type为'Red',通过实例化衣服类new Red()来生产红色的衣服。Interface.ensureImplements在鸭式辨型中提过。这里用来检测衣服是否实现了衣服接口(检测商品到底合不合格)。
Interface类
var Interface = function (name, methods) {if(!methods) {throw new Error('Methods is undefined.');}if(!Array.isArray(methods)) {throw new Error('Methods is not an array.');}this.name = name;this.methods = [];//自定义方法作为类的依据for(var i = 0, len = methods.length; i < len; i++) {var method = methods[i];if(typeof method !== 'string') {throw new Error('Method name expected to be a string.');break;}this.methods.push(method);} }
View Code
ensureImplements方法
Interface.ensureImplements = function () {var canFoundMethods = [];if(arguments.length < 2) {throw new Error('Arguments is expected at least 2.');}//取第二个参数("鸭子"的实例),称为参照对象for(var i = 1, len = arguments.length; i < len; i++) {var interface = arguments[i];//遍历参照对象的方法名称,对比检测对象。for(var j = 0, methodsLength = interface.methods.length; j < methodsLength; j++) {var method = interface.methods[j];if(!arguments[0][method] || typeof arguments[0][method] !== 'function') {//检测对象没有的方法名称则记录 canFoundMethods.push(method);}}}//最后输出没有的方法if(canFoundMethods.length) {throw new Error ('Method ' + canFoundMethods.join(',') + ' was not found.');} }
View Code
第二步:定义衣服接口Clothes。
//衣服接口。衣服是什么?自定义为衣服制造出来的,可以穿,可以洗,可以晒干的。 var Clothes = new Interface('Clothes', ['make', 'ware', 'wash', 'dry']);
定义一个衣服接口,并且自定义具有这四个特点的就是衣服。接口就是一个规则,用来检测对象具有某些方法的手段。
//定义红色衣服的模型。 var Red = function (){}; Red.prototype = {color: function (){return 'Red';},make: function (){},ware: function (){},wash: function (){},dry: function (){} }
定义衣服模型。按照这个模型可以生产很多红色的衣服new Red()。当然这里也可以是其它的衣服模型var Green = function (){},Green.prototype = {..};
第三步:实例化ClothesShop类,调用sellClothes方法。
//按照衣服门面店的模型,创建一个衣服店。当然也可以创建N个店,clothesShop1,clothesShop2... var clothesShop = new ClothesShop(); //指定你要的选的颜色,买新的衣服 var yourNewClothes = clothesShop.sellClothes('Red');
当clothesShop调用sellClothes方法时,就像顾客下订单,然后由店来生产衣服,检测,最后出售。简单的工厂模式完成了,可以高兴一下。但是还是存在着一点问题,这里存在clothesShop既是门店,也是生产衣服的工厂。明显不符合我们的逻辑。我们肯定想的是把工厂和门店要分开。
第四步:创建工厂对象
//===============工厂制造衣服==================//把制造工作交给工厂,商店只负责出售衣服,分工明确。 var clothesFactory = {createClothes: function (color) {var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray'];var clothes;for(var i = 0, len = clothesType.length; i < len; i++) {if(color === clothesType[i]){clothes = eval('new '+ color); //new Red(); }}//判断制造的是不是衣服。 Interface.ensureImplements(clothes, Clothes);//衣服出厂return clothes;} }
用一个名为clothesFactory的工厂对象来实现createClothes方法。这样要需要的时候就可以在sellClothes调用createClothes方法。
第五步:修改ClothesShop类
//创建一个衣服门店模型。 var ClothesShop = function (){} ClothesShop.prototype = {sellClothes: function (color){var clothes = clothesFactory.createClothes(color);//出售return clothes;} }
修改ClothesShop门店模型,只负责出售衣服。到这里简单工厂完成了。
完整代码:
clothes.js
1 /** 2 * Created by Song_yc on 2015/2/2. 3 */ 4 //创建一个衣服门面店模型。 5 var ClothesShop = function (){} 6 ClothesShop.prototype = { 7 sellClothes: function (color){ 8 var clothes = clothesFactory.createClothes(color); 9 //出售 10 return clothes; 11 } 12 } 13 /*门店1 14 var clothesShop1 = new ClothesShop(); 15 门店2 16 var clothesShop2 = new ClothesShop(); 17 门店3 18 var clothesShop3 = new ClothesShop();*/ 19 20 var Interface = function (name, methods) { 21 if(arguments.length !== 2) { 22 throw new Error('Interface constructor called with' + arguments.length + 'arguments, but expected exactly 2.'); 23 } 24 this.name = name; 25 this.methods = []; 26 if(!Array.isArray(methods)) { 27 throw new Error('The second argument is expected array object instance of ' + typeof method+ '.'); 28 } 29 for(var i = 0, len = methods.length; i < len; i++) { 30 var method = methods[i]; 31 if(typeof method !== 'string') { 32 throw new Error('Interface constructor expects method names to be as a string.'); 33 break; 34 } 35 this.methods.push(method); 36 } 37 } 38 39 Interface.ensureImplements = function () { 40 var canFoundMethods = []; 41 //First to determine argument's length. 42 if(arguments.length < 2) { 43 throw new Error('Arguments is expected at least 2.'); 44 } 45 //Second to determine instance class. 46 for(var i = 1, len = arguments.length; i < len; i++) { 47 var interface = arguments[i]; 48 if(interface.constructor !== Interface) { 49 throw new Error(interface.name + 'object is not instanced of Interface Class.'); 50 } 51 for(var j = 0, methodsLength = interface.methods.length; j < methodsLength; j++) { 52 var method = interface.methods[j]; 53 if(!arguments[0][method] || typeof arguments[0][method] !== 'function') { 54 //throw new Error('Method ' + method + 'was not found.'); 55 canFoundMethods.push(method); 56 } 57 } 58 } 59 //canFoundMethods.forEach(function (methodName) { 60 // throw new Error('Method ' + methodName + 'was not found.'); 61 //}) 62 if(canFoundMethods.length) { 63 throw new Error ('Method ' + canFoundMethods.join(',') + ' was not found.'); 64 } 65 } 66 //定义衣服类。衣服是什么?被制造出来的,可以穿,可以洗,可以晒干的。 67 var Clothes = new Interface('Clothes', ['make', 'ware', 'wash', 'dry']); 68 //定义红色衣服的模型。 69 var Red = function (){}; 70 Red.prototype = { 71 color: function (){return 'red';}, 72 make: function (){}, 73 ware: function (){}, 74 wash: function (){}, 75 dry: function (){} 76 } 77 78 //===============工厂制造衣服================== 79 80 //把制造工作交给工厂,商店只负责出售衣服,分工明确。 81 var clothesFactory = { 82 createClothes: function (color) { 83 var clothesType = ['Red', 'Blue', 'Yello', 'Green', 'Gray']; 84 var clothes; 85 for(var i = 0, len = clothesType.length; i < len; i++) { 86 if(color === clothesType[i]){ 87 clothes = eval('new '+ color); //new Red(); 88 } 89 } 90 //判断制造的是不是衣服。 91 Interface.ensureImplements(clothes, Clothes); 92 //衣服出厂 93 return clothes; 94 } 95 } 96 97 //按照衣服门面店的模型,创建一个衣服店。当然也可以创建N个店,clothes1,clothes2... 98 var clothesShop = new ClothesShop(); 99 //选择喜欢的颜色 100 var yourNewClothes = clothesShop.sellClothes('Red');
View Code
index.html
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><script src="clothes.js"></script> </body> </html>
View Code
最后看看新的衣服。
2.总结:
回顾一下:首先创建一个门店模型,拥有生产各色衣服的方法。然后定义衣服接口,创建红色衣服模型,通过接口检测衣服是否合格。实例化门店,门店按照顾客的喜好进行生产衣服,检测,出售。最后把门店生产独立设计成简单工厂,生产和门店分离。
- 简单工厂方法就是把创建类实例的方法放在外部对象,当实例化对象时在外部对象中进行。
转载于:https://www.cnblogs.com/Songyc/p/4268194.html
工厂模式一之简单工厂相关推荐
- 简单工厂模式练习:简单工厂模式在农场系统中实现
目录 前言 一.简单工厂模式 二.农场系统创建 1.先新建一个包.类以及抽象类 2.键入各类中代码 1 抽象产品角色 Fruit 2 实现产品角色 Apple 3实现产品角色 Grape 4实现 ...
- 设计模式学习笔记(三)工厂模式中的简单工厂、工厂方法和抽象工厂模式之间的区别
设计模式中的工厂模式(Factory Design pattern)是一个比较常用的创建型设计模式,其中可以细分为三种:简单工厂(Simple Factory).工厂方法(Factory Method ...
- JAVA工厂模式优缺点_简单工厂模式、工厂模式和抽象工厂模式区别及优缺点
各位小伙伴好,今天给大家主要介绍一下简单工厂模式.工厂模式和抽象工厂模式的区别及各自的优缺点. (本文实现语言为Python3) [前言] 众所周知今天所讲的内容是 设计模式的一类:对于设计模式这个概 ...
- java 工厂模式 计算器_简单工厂模式实现简易计算器
packageFactoryMethodPattern;/*创建人:czc 创建时间:2019/12/16 创建用途:简单工厂模式实现计算器--主界面*/ import javax.swing.*;i ...
- HeadFirst设计模式(四) - 工厂模式之1 - 简单工厂
2019独角兽企业重金招聘Python工程师标准>>> 为什么要使用工厂? 当看到new时,就会想到具体这个词. 是的,当使用new时,确实是在实例化一个具体累,所以用的确实是实现, ...
- python简单工厂模式_python版简单工厂模式
什么是简单工厂模式 工厂模式有一种非常形象的描述,建立对象的类就如一个工厂,而需要被建立的对象就是一个个产品:在工厂中加工产品,使用产品的人,不用在乎产品是如何生产出来的.从软件开发的角度来说,这样就 ...
- 《JAVA与模式》之简单工厂模式
在阎宏博士的<JAVA与模式>一书中开头是这样描述简单工厂模式的:简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式.简单工厂模式是由一个工厂 ...
- 工厂三兄弟之简单工厂模式(二)
2 简单工厂模式概述 简单工厂模式并不属于GoF 23个经典设计模式,但通常将它作为学习其他工厂模式的基础,它的设计思想很简单,其基本流程如下: 首先将需要创建的各种不同对象(例如各种不同的Chart ...
- 工厂三兄弟之简单工厂模式
本文转载自 :http://blog.csdn.net/lovelion/article/details/9300337 工厂模式是最常用的一类创建型设计模式,通常我们所说的工厂模式是指工厂方法模式, ...
最新文章
- android java包_android SDk中常用的java包介绍
- 中国SaaS死或生之六:逢场作戏or脚踏实地?
- Redis 实践笔记
- Python Django 一对多正向查询示例
- 五分钟教你在Go-Bigger中设计自己的游戏AI智能体
- Dubbo 一篇文章就够了:从入门到实战
- c# 读取写入excel单元格基本操作
- excel插入页码_Excel里毫不起眼的页眉页脚,居然有这3种高能用法!
- 图:图的邻接表创建、深度优先遍历和广度优先遍历代码实现
- 【原生态跨平台:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服务器上一对一的配置实现-篇幅2】...
- Bootstrap treeview 添加滚动条后 搜索完成滚动条自动移动到对应位置
- 请不要滥用SharedPreference
- axios的this指向_vue使用axios时this指向哪里
- 奥鹏刷分软件_【中国大学mooc刷课系统和奥鹏在线作业自动答案软件哪个好用】中国大学mooc刷课系统和奥鹏在线作业自动答案软件对比-ZOL下载...
- Swift网络请求 - RXSwift + PromiseKit + Moya
- Uncaught TypeError: marked is not a function
- 目标检测经典论文——YOLOv3论文翻译(纯中文版):YOLOv3:增量式的改进(YOLOv3: An Incremental Improvement)
- bailian2705
- 你是外包,麻烦不要随便偷吃公司的零食
- 古之成大事者必经三境界--王国维《人间词话》
热门文章
- 使用Android studio 创建svn分支
- 线性筛法 与 线性求欧拉函数 的计算模板
- cat 常用的日志分析架构方案_芯片失效分析常用方法及解决方案
- jdbc preparestatement 执行多条语句_jmeter获取JDBC响应做接口关联(三)
- 双系统格盘后因grub无法进入xp系统问题,将linux所在分区格后启动停在grub。。。无法进入系统
- 快速排序pascal程序
- 欧几里得空间——度量矩阵
- linux 文件io实例代码,linux 文件IO(示例代码)
- python有什么简单项目_python有什么简单项目适合初学者?
- php关键词分词搜索 最多匹配的排在最前面_图解 | 通用搜索引擎背后的技术点...