封装、信息隐藏与接口的关系
信息隐藏是目的,封装是手段。
接口提供了一份记载着可供公共访问的方法的契约。它定义了两个对象间可以具有的关系。只要接口不变,这个关系的双方都是可以替换的。
一个理想的软件系统应该为所有类定义接口。
创建对象的基本模式
1.门户大开型
var Publication = new Interface('Publication', ['getIsbn', 'setIsbn',...]); //接口 var Book = function(isbn, title, author){this.setIsbn(isbn);this.setTitle(title);this.setAuthor(author); }; Book.prototype = {checkIsbn: function(){...},getIsbn: function(){return this.isbn,}, //取值器setIsbn: function(isbn){this.isbn=isbn;}, //赋值器 ... };
接口+门户大开+取值器/赋值器是门户大开型创建对象所能达到的最好效果了。
2.命名规范区别私有成员。
var Publication = new Interface('Publication', ['getIsbn', 'setIsbn',...]); //接口 var Book = function(isbn, title, author){this.setIsbn(isbn);this.setTitle(title);this.setAuthor(author); }; Book.prototype = {checkIsbn: function(){...},getIsbn: function(){return this._isbn,}, //取值器setIsbn: function(isbn){this._isbn=isbn;}, //赋值器 ... };
没错,就是在变量的名字前面加个_来区别私有变量,这个也是众所周知的一种命名规范。
3.闭包实现私有成员
var Book = function(newIsbn, newTitle, newAuthor){var isbn, title, author; //私有function checkIsbn(isbn){} //私有this.getIsbn = function(){ //特权return isbn;};this.setIsbn = function(newIsbn){ //特权if(!checkIsbn(ewIsbn)) throw new Error('Book: invalid ISBN.');isbn = newIsbn;} };Book.prototype = { display: function(){ //公有 ...}; };
所谓特权方法就是说这个方法既是公用方法缺能够访问私有变量,故此称之为特权方法。
4.静态方法和属性(注意匿名函数是神来一笔)
前面创建对象时的大多数方法和属性所关联的是类的实例,而静态成员所关联的是类本身。每个静态成员只有一份。
var Book = (function(){var numOfBooks = 0; //private static attributefunction checkIsbn(){...}; //private static methodreturn function(newIsbn, newTitle, newAuthor){var isbn, title, author; //private attribute//privileged methodsthis.getIsbn = function(){return isbn;};this.setIsbn = function(){...};numOfBooks ++;if(numOfBooks > 50){throw new Error('Book: Only 50 instances of Book can be created.');}this.setIsbn(newIsbn);...}; })();//Public static method Book.convertToTitleCase = function(){... };//Public, non-privileged methods Book.prototype = {display: function(){...} };
想想闭包,琢磨一下numOfBooks这个变量,就知道这是怎么一回事了。
常量
在JS中我们可以通过创建只有取值器而没有赋值器的变量来模仿常量。具体的就不给出代码了。