javascript优化--10模式(设计模式)01
单体模式:保证一个特定类仅有一个实例;即第二次使用同一个类创建新对象时,应该得到与第一个所创建对象完全相同对象;
- 在JS中,可以认为每次在使用对象字面量创建对象的时候,实际上就在创建一个单体;
- 当使用new创建新对象时
- 使用静态属性中的实例:
- function Universe() {
- if(typeof Universe.instance === 'object') {
- return Universe.instance;
- }
- this.start_time = 0;
- this.bang = 'Big';
- Universe.instance = this;
- return this;
- }
- function Universe() {
- 采用闭包包含单个实例:
- function Universe1() {
- var instance = this;
- this.start_time = 0;
- this.bang = 'Big';
- Universe1 = function() {
- return instance;
- }
- }
- var Universe;
- (function () {
- var instance;
- Universe = function Universe() {
- if(instance) {
- return instance;
- }
- instance = this;
- //增加功能
- this.start_time = 0;
- this.bang = 'Big';
- }
- })();
- function Universe1() {
- 使用静态属性中的实例:
工厂模式:
根据字符串指定地类型在运行时创建对象地方法
工厂模式地目的使为了创建对象
- 当创建对象时执行重复操作
- 再编译时不知道具体类型地情况下,为工厂客户提供一个创建对象的接口
- function CarMaker() {};
- CarMaker.prototype.drive = function() {
- return "Vroom, I have " + this.doors + " doors";
- };
- CarMaker.factory = function(type) {
- var constr = type, newcar;
- //如果构造函数不存在,则抛出错误
- if(typeof CarMaker[constr] != "function") {
- throw {
- name: "Error",
- message: constr + " doesn't exist"
- };
- }
- //构造函数是已知存在的;使原型继承父类,但仅继承一次
- if(typeof CarMaker[constr].prototype.drive !== 'function') {
- CarMaker[constr].prototype = new CarMaker();
- }
- //创建一个新的实例
- newcar = new CarMaker[constr]();
- //选择性地调用一些方法,然后返回
- return newcar;
- };
- CarMaker.Compact = function() {
- this.doors = 4;
- };
- CarMaker.Convertible = function() {
- this.doors = 2;
- }
- CarMaker.SUV = function() {
- this.doors = 24;
- }
- var corolla = CarMaker.factory('Compact');
- var solstice = CarMaker.factory('Convertible');
- var cherokee = CarMaker.factory('SUV');
- corolla.drive();
- solstice.drive();
- cherokee.drive();
内置对象工厂:对于自然工厂的例子,可以考虑内置的Object()构造函数;它也根据输入类型而创建不同的对象;
迭代器模式:
提供一个API来遍历或操纵复杂地自定义数据结构
迭代访问一个包含某些数据集合的对象的模式;
- var agg = (function() {
- var index = 0, data = [1,2,3,4,5], length = data.length;
- return {
- next: function() {
- var element;
- if(!this.hasNext()) {
- return null;
- }
- element = data[index];
- index = index + 2;
- return element;
- },
- hasNext: function() {
- return index < length;
- },
- //重置指针到初始化位置
- rewind: function() {
- index = 0;
- },
- //返回当前元素
- current: function() {
- return data[index];
- }
- }
- }());
- //测试
- while(agg.hasNext()) {
- console.log(agg.next());
- }
- agg.rewind();
- console.log(agg.current());
装饰者模式
可以再运行时动态添加附加功能到对象中;比较方便的特征时其预期行为可制定和可配置;
- function Sale(price) {
- this.price = price || 100;
- }
- Sale.prototype.getPrice = function() {
- return this.price;
- }
- Sale.decorators = {};
- //增加联邦税
- Sale.decorators.fedtax = {
- getPrice: function() {
- var price = this.uber.getPrice();
- price += price * 5/ 100;
- return price;
- }
- };
- //增加省级税
- Sale.decorators.quebec = {
- getPrice: function() {
- var price = this.uber.getPrice();
- price += price * 7.5 /100;
- return price;
- }
- };
- //转化为美元
- Sale.decorators.money = {
- getPrice: function() {
- return "$" + this.uber.getPrice().toFixed(2);
- }
- };
- //格式化为CDN
- Sale.decorators.cdn = {
- getPrice: function() {
- return "CDN$ " + this.uber.getPrice().toFixed(2);
- }
- };
- Sale.prototype.decorate = function(decorator) {
- var F = function() {},
- overrides = this.constructor.decorators[decorator],
- i, newobj;
- F.prototype = this;
- newobj = new F();
- newobj.uber = F.prototype;
- for(i in overrides) {
- if(overrides.hasOwnProperty(i)) {
- newobj[i] = overrides[i];
- }
- }
- return newobj;
- }
- var sale = new Sale(100);
- sale = sale.decorate('fedtax');
- sale = sale.decorate('quebec');
- sale = sale.decorate('money');
- sale.getPrice();
- var newsale = new Sale(200);
- newsale = newsale.decorate('cdn');
- newsale.getPrice();
使用列表实现
- function Sale(price) {
- this.price = price;
- this.decorators_list = [];
- }
- Sale.decorators = {};
- Sale.decorators.fedtax = {
- getPrice: function(price) {
- return price + price * 5 / 100;
- }
- };
- Sale.decorators.quebec = {
- getPrice: function(price) {
- return price + price * 7.5 /100;
- }
- };
- Sale.decorators.money = {
- getPrice: function(price) {
- return "$" + price.toFixed(2);
- }
- };
- Sale.prototype.decorate = function(decorator) {
- this.decorators_list.push(decorator)
- };
- Sale.prototype.getPrice = function() {
- var price = this.price, i, max = this.decorators_list.length, name;
- for(i = 0; i < max; i++) {
- name = this.decorators_list[i];
- price = Sale.decorators[name].getPrice(price);
- }
- return price;
- }
- var sale = new Sale(100);
- sale.decorate('fedtax');
- sale.decorate('quebec');
- sale.decorate('money');
- console.log(sale.getPrice());
javascript优化--10模式(设计模式)01的更多相关文章
- javascript优化--11模式(设计模式)02
策略模式 在选择最佳策略以处理特定任务(上下文)的时候仍然保持相同的接口: //表单验证的例子 var data = { firs_name: "Super", last_name ...
- javascript优化--06模式(对象)01
命名空间: 优点:可以解决命名混乱和第三方冲突: 缺点:长嵌套导致更长的查询时间:更多的字符: 通用命名空间函数: var MYAPP = MYAPP || {}; MYAPP.namespace = ...
- javascript优化--12模式(设计模式)03
观察者模式 通过创建一个可观察的对象,当发生一个感兴趣的事件时将该事件通告给所有观察者,从而形成松散的耦合 订阅杂志 //发布者对象 var publisher = { subscribers: { ...
- javascript优化--08模式(代码复用)01
优先使用对象组合,而不是类继承: 类式继承:通过构造函数Child()来获取来自于另一个构造函数Parent()的属性: 默认模式:子类的原型指向父类的一个实例 function inherit(C, ...
- javascript优化--13模式1(DOM和浏览器模式)
注意分离: 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读: 将JavaScript关闭来测试页面仍然可以执行正常功能:所有连接是否正常工作:所有的表单是否可以正常工作: 不使用内联处理器( ...
- javascript优化--14模式2(DOM和浏览器模式)
远程脚本 XMLHttpRequest JSONP 和XHR不同,它不受同域的限制: JSONP请求的可以是任意的文档: 请求的URL通常格式为http://example.js?calback=Ca ...
- javascript优化--05模式(函数)
回调函数模式: 基本例子: var findNodes = function (callback) { ...................... if (typeof callback !== ' ...
- javascript优化--09模式(代码复用)02
原型继承 ://现代无类继承模式 基本代码: var parent = { name : "Papa" } var child = object(parent); function ...
- javascript优化--07模式(对象)02
沙箱模式: 解决空间命名模式的几个缺点: 命名空间模式中无法同时使用一个应用程序或库的两个版本运行在同一个页面中,因为两者需要相同的全局符号: 以点分割,需要输入更长的字符,解析时间也更长: 全局构造 ...
随机推荐
- Matlab之字符串处理
Matlab处理字符串 1.取得部分字符串 我们有一个字符串 file='20131030_113109.TemporaryAlias.Poly5'; 简单操作举例: >> a=file( ...
- Parencodings(imitate)
Parencodings Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 20679 Accepted: 12436 De ...
- IE下的haslayout特性
什么是hasLayout?hasLayout是IE特有的一个属性.很多的ie下的css bug都与其息息相关.在ie中,一个元素要么自己对自身的内容进行计算大小和组织,要么依赖于父元素来计算尺寸和组织 ...
- 一个1年前的T-SQL问题
还记得年前的一个SQL问题,当时对SQL刚接触,因此绕开了它.用了别的办法.昨天看SQL突然想起了这个问题.百思不得其解,然后去SQL Server技术交流群,也请教了,大神高文佳,何志勇提示我因为先 ...
- [Effective JavaScript 笔记]第4章:对象和原型--个人总结
前言 对象是js中的基本数据结构.对象在js语言编码中也随处可见,比如经常会用到的函数,也是一个Function构造函数,Function.prototype原型对象.每当声明一个函数时,都会继承Fu ...
- sql分页查询语句
有关分页 SQL 的资料很多,有的使用存储过程,有的使用游标.本人不喜欢使用游标,我觉得它耗资.效率低:使用存储过程是个不错的选择,因为存储过程是经过预编译的,执行效率高,也更灵活.先看看单条 SQL ...
- HDU1879 kruscal 继续畅通工程
继续畅通工程 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Subm ...
- php页面打开响应时间
$start_time = array_sum(explode(' ',microtime())); //your code here $end_time = array_sum(explode( ...
- cookie注入的形成,原理,利用总结
一:cookie注入的形成 程序对提交数据获取方式是直接request("c.s.t")的方式.未指明使用request对象的具体方法进行获取. 二:原理 request(&quo ...
- 【Python】python代码如何调试?
Python 程序如何高效地调试? 现在我在debug python程序就只是简单在有可能错误的地方print出来看一下,不知道python有没像c++的一些IDE一样有单步调试这类的工具?或者说各位 ...