`
mabusyao
  • 浏览: 252724 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

JavaScript Design Pattern - 2. Interface

阅读更多
想要在JavaScript中应该面向对象的设计模式,首先就需要JavaScript支持某些面向对象的语言特性,比如说继承,封装,多态等等。至于这些语言特性所带来的好处,这里就不多说了。如果你并不打算使用JavaScript设计非常复杂的应用,你也应该对这些东西有所了解,至少它可以帮助你把代码写的更简洁,同时它也提供了一些写JavaScript代码的新思路。


为何要模拟接口?(Interface)

接口(Interface)是面向对象语言中很重要的一个概念,它为协作的开发人员提供了一个统一的开发协议,“面向接口编程而不是面向实现编程”是每个OO程序员都必须要知道的基本准则。同时,也有很多设计模式是基于Interface来实现的:

1. 工厂模式(factory pattern)
工厂对象负责替程序动态的产生某一类对象,这些产生的对象通常都继承于同一接口。

2. 组件模式(composite pattern)
如果没有接口,你基本上无法实现组件模式(抽象类好像可以)。

3.装饰器模式(decorator pattern)
装饰器模式为已有的对象提供了一种无需修改就能增加新的功能的方法。我们采用接口来定义装饰类所需提供的新功能。

4. 命令模式(command pattern)
通过接口我们定义出每个command类所必须要提供的方法。


如果模拟接口?

定义一个接口对象,并提供方法检测某个对象是否完全实现了该接口的方法:
/**
 * Constructor
 * How to use Interface:
 * 	var MyWork = new Interface("MyWork", ["getName", "getValue"]);
 * 	Interface.ensureImplements(results, MyWork);
 * 
 * @param name
 * @param methods
 * @returns
 */
var Interface = function(name, methods) {
	if (arguments.length != 2) {
		throw new Error("Interface constructor called with " + arguments.length
				+ "arguments, but expected exactly 2.");
	}
	
	this.name = name;
	this.methods = [];
	for ( var i = 0, len = methods.length; i < len; i++) {
		if (typeof methods[i] !== 'string') {
			throw new Error("Interface constructor expects method names to be "
					+ "passed in as a string.");
		}
		this.methods.push(methods[i]);
	}
};

/**
 * If the object valid for interfaces.
 * @param object
 * @param interfaces...
 */
Interface.ensureImplements = function(object) {
	if (arguments.length < 2) {
		throw new Error("Function Interface.ensureImplements called with "
				+ arguments.length + "arguments, but expected at least 2.");
	}
	for ( var i = 1, len = arguments.length; i < len; i++) {
		var interface = arguments[i];
		if (interface.constructor !== Interface) {
			throw new Error(
					"Function Interface.ensureImplements expects arguments"
							+ "two and above to be instances of Interface.");
		}
		for ( var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
			var method = interface.methods[j];
			if (!object[method] || typeof object[method] !== 'function') {
				throw new Error("Function Interface.ensureImplements: object "
						+ "does not implement the " + interface.name
						+ " interface. Method " + method + " was not found.");
			}
		}
	}
};


当使用时, 先new一个Interface对象:
var DynamicMap = new Interface('DynamicMap', ['centerOnPoint', 'zoom', 'draw']);

这个Interface对象中,定义了DynamicMap这个接口所有的方法声明。

然后对于应该继承该接口的对象,检测它是否真实的定义了所有方法:
function displayRoute(mapInstance) {
Interface.ensureImplements(mapInstace, DynamicMap);
mapInstance.centerOnPoint(12, 34);
mapInstance.zoom(5);
mapInstance.draw();
...
}
分享到:
评论

相关推荐

    基于python的小区监控图像拼接系统源码数据库论文.doc

    Additionally, considering the potential need for system maintenance, the B/S (Browser/Server) design pattern was utilized, allowing server-side updates without requiring any changes on the client-...

    Ajax in Action

    - Using the MVC pattern with JavaScript. - Separating presentation from logic for maintainable code. - Creating a flexible event-handling model. - Generating the user interface directly from ...

    Learning Angular - Fourth Edition A no-nonsense guide to building web applications with Angular 15 (Aristeidis Bampakos, Pablo Deeleman) (Z-Library).pdf

    - **Improved CLI**: The Angular CLI (Command Line Interface) is enhanced with more efficient build and development workflows, making it easier for developers to generate and manage project assets. ...

    TypeScript Design Patterns.pdf

    《TypeScript Design Patterns》这本书由资深JavaScript工程师Vilic Vane撰写,该书详细介绍了如何在TypeScript中运用各种设计模式来提升软件开发效率。Vilic Vane拥有超过八年的Web开发经验,并且自TypeScript公开...

    基于微信公众平台的微商城研究与设计.docx

    Django follows an Model-View-Controller (MVC) architectural pattern and promotes the use of reusable and pluggable components, making it ideal for developing complex web applications like a micro ...

    udacity-js-design-pattern:[实践代码]学习Javascript

    本项目"udacity-js-design-pattern"聚焦于通过实践来学习JavaScript设计模式,特别通过名为"Cat Clicker"的项目来体现这一学习过程。 在"Cat Clicker"项目中,我们可以看到三个不同阶段的实现,即"try1"、"try2"和...

    外文翻译 stus MVC

    Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains...

    基于ssm+mysql的大创项目申报管理系统源码数据库论文.docx

    The development process typically involves designing the UI using HTML, CSS, and JavaScript for a user-friendly interface, followed by server-side development using Java and the SSM framework....

    基于ssm+mysql的健身房众筹系统源码数据库论文.doc

    The MVC design pattern is crucial in separating concerns, dividing the application into three distinct parts: Model (data management), View (user interface), and Controller (communication between ...

    Msdn Magazine Feb. 2012

    - **Custom Controls**: Instructions on creating custom controls using JavaScript and CSS for a more engaging user interface. - **Accessibility**: Tips for making ...

    基于springboot+vue的早餐店点餐系统源码数据库论文.doc

    The B/S (Browser/Server) design pattern is utilized here, where the client-side interface interacts with the server-side logic through web browsers, enabling remote access and efficient data exchange...

    html登录页面login087.rar

    2. **自适应设计(Responsive Web Design, RWD)** 自适应设计使网页可以根据用户设备的屏幕尺寸和方向调整布局。在这个登录页面中,可能使用了媒体查询(Media Queries)来定义不同屏幕尺寸下的样式规则。例如: ...

    计算机编程英语词汇 .

    8. **软件工程术语**:algorithm(算法)、design pattern(设计模式)、debugging(调试)、compilation(编译)、interpretation(解释)、runtime(运行时),这些术语涵盖了软件开发的全过程。 9. **网络编程**...

    UI界面设计中的工具[汇编].pdf

    10. **User Interface Design Framework**: 这是一个免费的网页设计师资源库,提供用户界面设计模板和框架,便于设计师快速启动项目。 11. **Pattern Tap**: Pattern Tap提供了一系列设计资源和模式,帮助设计师...

    Django 1.0 Website Development.pdf

    MVC pattern in web development 7 Why Python? 8 Why Django? 9 Tight integration between components 10 Object-Relational Mapper 10 Clean URL design 10 Automatic administration interface 10 ...

    计算机英语

    5. **软件工程**:软件工程的英文词汇如`requirements analysis`(需求分析)、`design pattern`(设计模式)、`debugging`(调试)、`version control`(版本控制)、`unit testing`(单元测试)等,它们构成了软件...

    计算机编程英语单词汇总.pdf

    design pattern 设计模式设计模式是解决常见软件设计问题的模板,提供了可复用的解决方案。 device driver 设备驱动程序设备驱动程序是操作系统与硬件设备之间的桥梁,使操作系统能够与硬件通信。 DLL (Dynamic ...

Global site tag (gtag.js) - Google Analytics