创建型模式

1、FACTORY—追MM少不了请吃饭了,麦当劳的鸡翅和肯德基的鸡翅都是MM爱吃的东西,虽然口味有所不同,但不管你带MM去麦当劳或肯德基,只管向服务员说“来四个鸡翅”就行了。麦当劳和肯德基就是生产鸡翅的Factory

工厂模式:客户类和工厂类分开。消费者任何时候需要某种产品,只需向工厂请求即可。消费者无须修改就可以接纳新产品。缺点是当产品修改时,工厂类也要做相应的修改。如:如何创建及如何向客户端提供。

2、BUILDER—MM最爱听的就是“我爱你”这句话了,见到不同地方的MM,要能够用她们的方言跟她说这句话哦,我有一个多种语言翻译机,上面每种语言都有一个按键,见到MM我只要按对应的键,它就能够用相应的语言说出“我爱你”这句话了,国外的MM也可以轻松搞掂,这就是我的“我爱你”builder。(这一定比美军在伊拉克用的翻译机好卖)

建造模式:将产品的内部表象和产品的生成过程分割开来,从而使一个建造过程生成具有不同的内部表象的产品对象。建造模式使得产品内部表象可以独立的变化,客户不必知道产品内部组成的细节。建造模式可以强制实行一种分步骤进行的建造过程。

3、FACTORY METHOD—请MM去麦当劳吃汉堡,不同的MM有不同的口味,要每个都记住是一件烦人的事情,我一般采用Factory Method模式,带着MM到服务员那儿,说“要一个汉堡”,具体要什么样的汉堡呢,让MM直接跟服务员说就行了。

工厂方法模式:核心工厂类不再负责所有产品的创建,而是将具体创建的工作交给子类去做,成为一个抽象工厂角色,仅负责给出具体工厂类必须实现的接口,而不接触哪一个产品类应当被实例化这种细节。

4、PROTOTYPE—跟MM用QQ聊天,一定要说些深情的话语了,我搜集了好多肉麻的情话,需要时只要copy出来放到QQ里面就行了,这就是我的情话prototype了。(100块钱一份,你要不要)

原始模型模式:通过给出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的方法创建出更多同类型的对象。原始模型模式允许动态的增加或减少产品类,产品类不需要非得有任何事先确定的等级结构,原始模型模式适用于任何的等级结构。缺点是每一个类都必须配备一个克隆方法。

5、SINGLETON—俺有6个漂亮的老婆,她们的老公都是我,我就是我们家里的老公Sigleton,她们只要说道“老公”,都是指的同一个人,那就是我(刚才做了个梦啦,哪有这么好的事)

单例模式:单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用。

结构型模式

6、ADAPTER—在朋友聚会上碰到了一个美女Sarah,从香港来的,可我不会说粤语,她不会说普通话,只好求助于我的朋友kent了,他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了(也不知道他会不会耍我)

适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。

7、BRIDGE—早上碰到MM,要说早上好,晚上碰到MM,要说晚上好;碰到MM穿了件新衣服,要说你的衣服好漂亮哦,碰到MM新做的发型,要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”这种问题,自己用BRIDGE组合一下不就行了

桥梁模式:将抽象化与实现化脱耦,使得二者可以独立的变化,也就是说将他们之间的强关联变成弱关联,也就是指在一个软件系统的抽象化和实现化之间使用组合/聚合关系而不是继承关系,从而使两者可以独立的变化。

8、COMPOSITE—Mary今天过生日。“我过生日,你要送我一件礼物。”“嗯,好吧,去商店,你自己挑。”“这件T恤挺漂亮,买,这条裙子好看,买,这个包也不错,买。”“喂,买了三件了呀,我只答应送一件礼物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻烦你包起来。”“……”,MM都会用Composite模式了,你会了没有?

合成模式:合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树结构表示出来。合成模式使得客户端把一个个单独的成分对象和由他们复合而成的合成对象同等看待。

9、DECORATOR—Mary过完轮到Sarly过生日,还是不要叫她自己挑了,不然这个月伙食费肯定玩完,拿出我去年在华山顶上照的照片,在背面写上“最好的的礼物,就是爱你的Fita”,再到街上礼品店买了个像框(卖礼品的MM也很漂亮哦),再找隔壁搞美术设计的Mike设计了一个漂亮的盒子装起来……,我们都是Decorator,最终都在修饰我这个人呀,怎么样,看懂了吗?

装饰模式:装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,提供比继承更多的灵活性。动态给一个对象增加功能,这些功能可以再动态的撤消。增加由一些基本功能的排列组合而产生的非常大量的功能。

10、FACADE—我有一个专业的Nikon相机,我就喜欢自己手动调光圈、快门,这样照出来的照片才专业,但MM可不懂这些,教了半天也不会。幸好相机有Facade设计模式,把相机调整到自动档,只要对准目标按快门就行了,一切由相机自动调整,这样MM也可以用这个相机给我拍张照片了。

门面模式:外部与一个子系统的通信必须通过一个统一的门面对象进行。门面模式提供一个高层次的接口,使得子系统更易于使用。每一个子系统只有一个门面类,而且此门面类只有一个实例,也就是说它是一个单例模式。但整个系统可以有多个门面类。

11、FLYWEIGHT—每天跟MM发短信,手指都累死了,最近买了个新手机,可以把一些常用的句子存在手机里,要用的时候,直接拿出来,在前面加上MM的名字就可以发送了,再不用一个字一个字敲了。共享的句子就是Flyweight,MM的名字就是提取出来的外部特征,根据上下文情况使用。

享元模式:FLYWEIGHT在拳击比赛中指最轻量级。享元模式以共享的方式高效的支持大量的细粒度对象。享元模式能做到共享的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部,不会随环境的改变而有所不同。外蕴状态是随环境的改变而改变的。外蕴状态不能影响内蕴状态,它们是相互独立的。将可以共享的状态和不可以共享的状态从常规类中区分开来,将不可以共享的状态从类里剔除出去。客户端不可以直接创建被共享的对象,而应当使用一个工厂对象负责创建被共享的对象。享元模式大幅度的降低内存中对象的数量。

12、PROXY—跟MM在网上聊天,一开头总是“hi,你好”,“你从哪儿来呀?”“你多大了?”“身高多少呀?”这些话,真烦人,写个程序做为我的Proxy吧,凡是接收到这些话都设置好了自动的回答,接收到其他的话时再通知我回答,怎么样,酷吧。

代理模式:代理模式给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用。代理就是一个人或一个机构代表另一个人或者一个机构采取行动。某些情况下,客户不想或者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客户端分辨不出代理主题对象与真实主题对象。代理模式可以并不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,这时候代理对象不能够创建被代理对象,被代理对象必须有系统的其他角色代为创建并传入。

行为模式

13、CHAIN OF RESPONSIBLEITY—晚上去上英语课,为了好开溜坐到了最后一排,哇,前面坐了好几个漂亮的MM哎,找张纸条,写上“Hi,可以做我的女朋友吗?如果不愿意请向前传”,纸条就一个接一个的传上去了,糟糕,传到第一排的MM把纸条传给老师了,听说是个老处女呀,快跑!

责任链模式:在责任链模式中,很多对象由每一个对象对其下家的引用而接

起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。客户并不知道链上的哪一个对象最终处理这个请求,系统可以在不影响客户端的情况下动态的重新组织链和分配责任。处理者有两个选择:承担责任或者把责任推给下家。一个请求可以最终不被任何接收端对象所接受。
14、COMMAND—俺有一个MM家里管得特别严,没法见面,只好借助于她弟弟在我们俩之间传送信息,她对我有什么指示,就写一张纸条让她弟弟带给我。这不,她弟弟又传送过来一个COMMAND,为了感谢他,我请他吃了碗杂酱面,哪知道他说:“我同时给我姐姐三个男朋友送COMMAND,就数你最小气,才请我吃面。”,:-(

命令模式:命令模式把一个请求或者操作封装到一个对象中。命令模式把发出命令的责任和执行命令的责任分割开,委派给不同的对象。命令模式允许请求的一方和发送的一方独立开来,使得请求的一方不必知道接收请求的一方的接口,更不必知道请求是怎么被接收,以及操作是否执行,何时被执行以及是怎么被执行的。系统支持命令的撤消。

15、INTERPRETER—俺有一个《泡MM真经》,上面有各种泡MM的攻略,比如说去吃西餐的步骤、去看电影的方法等等,跟MM约会时,只要做一个Interpreter,照着上面的脚本执行就可以了。

解释器模式:给定一个语言后,解释器模式可以定义出其文法的一种表示,并同时提供一个解释器。客户端可以使用这个解释器来解释这个语言中的句子。解释器模式将描述怎样在有了一个简单的文法后,使用模式设计解释这些语句。在解释器模式里面提到的语言是指任何解释器对象能够解释的任何组合。在解释器模式中需要定义一个代表文法的命令类的等级结构,也就是一系列的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的等级结构中的对象的任何排列组合都是一个语言。

16、ITERATOR—我爱上了Mary,不顾一切的向她求婚。

Mary:“想要我跟你结婚,得答应我的条件”

我:“什么条件我都答应,你说吧”

Mary:“我看上了那个一克拉的钻石”

我:“我买,我买,还有吗?”

Mary:“我看上了湖边的那栋别墅”

我:“我买,我买,还有吗?”

Mary:“你的小弟弟必须要有50cm长”

我脑袋嗡的一声,坐在椅子上,一咬牙:“我剪,我剪,还有吗?”

……

迭代子模式:迭代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起形成的总体称之为聚集,聚集对象是能够包容一组对象的容器对象。迭代子模式将迭代逻辑封装到一个独立的子对象中,从而与聚集本身隔开。迭代子模式简化了聚集的界面。每一个聚集对象都可以有一个或一个以上的迭代子对象,每一个迭代子的迭代状态可以是彼此独立的。迭代算法可以独立于聚集角色变化。

17、MEDIATOR—四个MM打麻将,相互之间谁应该给谁多少钱算不清楚了,幸亏当时我在旁边,按照各自的筹码数算钱,赚了钱的从我这里拿,赔了钱的也付给我,一切就OK啦,俺得到了四个MM的电话。

调停者模式:调停者模式包装了一系列对象相互作用的方式,使得这些对象不必相互明显作用。从而使他们可以松散偶合。当某些对象之间的作用发生改变时,不会立即影响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的相互作用转化为一对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在小尺度的行为上与其他对象的相互作用分开处理。

18、MEMENTO—同时跟几个MM聊天时,一定要记清楚刚才跟MM说了些什么话,不然MM发现了会不高兴的哦,幸亏我有个备忘录,刚才与哪个MM说了什么话我都拷贝一份放到备忘录里面保存,这样可以随时察看以前的记录啦。

备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏封装的条件下,将一个对象的状态捉住,并外部化,存储起来,从而可以在将来合适的时候把这个对象还原到存储起来的状态。

19、OBSERVER—想知道咱们公司最新MM情报吗?加入公司的MM情报邮件组就行了,tom负责搜集情报,他发现的新情报不用一个一个通知我们,直接发布给邮件组,我们作为订阅者(观察者)就可以及时收到情报啦

观察者模式:观察者模式定义了一种一队多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。

20、STATE—跟MM交往时,一定要注意她的状态哦,在不同的状态时她的行为会有不同,比如你约她今天晚上去看电影,对你没兴趣的MM就会说“有事情啦”,对你不讨厌但还没喜欢上的MM就会说“好啊,不过可以带上我同事么?”,已经喜欢上你的MM就会说“几点钟?看完电影再去泡吧怎么样?”,当然你看电影过程中表现良好的话,也可以把MM的状态从不讨厌不喜欢变成喜欢哦。

状态模式:状态模式允许一个对象在其内部状态改变的时候改变行为。这个对象看上去象是改变了它的类一样。状态模式把所研究的对象的行为包装在不同的状态对象里,每一个状态对象都属于一个抽象状态类的一个子类。状态模式的意图是让一个对象在其内部状态改变的时候,其行为也随之改变。状态模式需要对每一个系统可能取得的状态创立一个状态类的子类。当系统的状态变化时,系统便改变所选的子类。

21、STRATEGY—跟不同类型的MM约会,要用不同的策略,有的请电影比较好,有的则去吃小吃效果不错,有的去海边浪漫最合适,单目的都是为了得到MM的芳心,我的追MM锦囊中有好多Strategy哦。

策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。策略模式把行为和环境分开。环境类负责维持和查询行为类,各种算法在具体的策略类中提供。由于算法和环境独立开来,算法的增减,修改都不会影响到环境和客户端。

22、TEMPLATE METHOD——看过《如何说服女生上床》这部经典文章吗?女生从认识到上床的不变的步骤分为巧遇、打破僵局、展开追求、接吻、前戏、动手、爱抚、进去八大步骤(Template method),但每个步骤针对不同的情况,都有不一样的做法,这就要看你随机应变啦(具体实现);

模板方法模式:模板方法模式准备一个抽象类,将部分逻辑以具体方法以及具体构造子的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。先制定一个顶级逻辑框架,而将逻辑的细节留给具体的子类去实现。

23、VISITOR—情人节到了,要给每个MM送一束鲜花和一张卡片,可是每个MM送的花都要针对她个人的特点,每张卡片也要根据个人的特点来挑,我一个人哪搞得清楚,还是找花店老板和礼品店老板做一下Visitor,让花店老板根据MM的特点选一束花,让礼品店老板也根据每个人特点选一张卡,这样就轻松多了;

访问者模式:访问者模式的目的是封装一些施加于某种数据结构元素之上的操作。一旦这些操作需要修改的话,接受这个操作的数据结构可以保持不变。访问者模式适用于数据结构相对未定的系统,它把数据结构和作用于结构上的操作之间的耦合解脱开,使得操作集合可以相对自由的演化。访问者模式使得增加新的操作变的很容易,就是增加一个新的访问者类。访问者模式将有关的行为集中到一个访问者对象中,而不是分散到一个个的节点类中。当使用访问者模式时,要将尽可能多的对象浏览逻辑放在访问者类中,而不是放到它的子类中。访问者模式可以跨过几个类的等级结构访问属于不同的等级结构的成员类。

转http://java.ccidnet.com/art/3749/20060622/586221_3.html

posted @ 2007-01-27 23:05 海思 阅读(79) | 评论 (0) | 编辑 收藏

2007年1月21日 #

Object Hierarchy and Inheritance in JavaScript

Object Hierarchy and Inheritance in JavaScript

JavaScript is an object-oriented language based on prototypes, rather than, as is common, being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This paper attempts to clarify the situation. If you're interested in precise details of how this all works, you can read the ECMA-262 JavaScript language specification (as a PDF file or a Microsoft Word self-extracting binary).
This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see Chapter 10, "Object Model," in the JavaScript Guide.
The sections in this paper are:

  • The Employee Example Creating the Hierarchy Object Properties More Flexible Constructors Property Inheritance Revisited

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A class defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the Employee class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less).
A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.
In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.
JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.
In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only name and dept properties and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.
JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the Employee-Manager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, specifying the reports property. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.
In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.
Table 1 gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

Table 1 Comparison of class-based (Java) and prototype-based (JavaScript) object systems

Class-based (Java) Prototype-based (JavaScript)
Class and instance are distinct entities. All objects are instances.
Define a class with a class definition; instantiate a class with constructor methods. Define and create a set of objects with constructor functions.
Create a single object with the new operator. Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes. Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain. Inherit properties by following the prototype chain.
Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime. Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
 

The Employee Example

The rest of this paper works with the simple employee hierarchy shown in Figure 1.
Figure 1    A simple object hierarchy

  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".

    Creating the Hierarchy

    There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later.
    For now, let's use very simple (and comparatively inflexible) definitions just to see how we get the inheritance to work. In these definitions, you can't specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time. Figure 2 illustrates the hierarchy with these simple definitions.
    In a real application, you would probably define constructors that allow you to provide property values at object creation time. Options for doing so are described later in "More Flexible Constructors". For now, these simple definitions let us look at how the inheritance occurs.
    Figure 2    What the definitions look like

    The simple Java and JavaScript Employee definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class.

    JavaScript

    Java
    function Employee () {    this.name = "";    this.dept = "general";}
    public class Employee {   public String name;   public String dept;   public Employee () {      this.name = "";      this.dept = "general";   }}
     

    The Manager and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

    JavaScript

    Java
    function Manager () {    this.reports = [];}Manager.prototype = new Employee;
    function WorkerBee () {    this.projects = [];}WorkerBee.prototype = new Employee;
    public class Manager extends Employee {   public Employee[] reports;   public Manager () {      this.reports = new Employee[0];   }}
    public class WorkerBee extends Employee {   public String[] projects;   public WorkerBee () {      this.projects = new String[0];   }}
     

    The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

    JavaScript

    Java
    function SalesPerson () {   this.dept = "sales";   this.quota = 100;}SalesPerson.prototype = new WorkerBee;
    function Engineer () {   this.dept = "engineering";   this.machine = "";}Engineer.prototype = new WorkerBee;
    public class SalesPerson extends WorkerBee {   public double quota;   public SalesPerson () {      this.dept = "sales";      this.quota = 100.0;   }}
    public class Engineer extends WorkerBee {   public String machine;   public Engineer () {      this.dept = "engineering";      this.machine = "";   }}
     

    Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

    NOTE: As described earlier, the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.

    Figure 3    Creating objects with the simple definitions

    Object Properties

    This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.

    Inheriting Properties

    Assume you create the mark object as a WorkerBee as shown in Figure 3 with this statement:

    mark = new WorkerBee;

    When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property. It also sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has 2 underscore characters at the front and 2 at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.
    This process doesn't explicitly put values in the mark object (local values) for the properties mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, the mark object has the following properties and values:

    mark.name = "";mark.dept = "general";mark.projects = [];

    The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in "Property Inheritance Revisited".
    Because these constructors don't let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as shown here:

    mark.name = "Doe, Mark";mark.dept = "admin";mark.projects = ["navigator"];

    Adding Properties

    In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in:

    mark.bonus = 3000;

    Now, the mark object has a bonus property, but no other WorkerBee has this property.
    If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

    Employee.prototype.specialty = "none";

    As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". Figure 4 shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.
    Figure 4    Adding properties

    More Flexible Constructors

    The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. Figure 5 shows one way to do this.
    Figure 5    Specifying properties in a constructor, take 1

    Here are the Java and JavaScript definitions for these objects.

    JavaScript

    Java
    function Employee (name, dept) {    this.name = name || "";    this.dept = dept || "general";}
    public class Employee {   public String name;   public String dept;   public Employee () {      this("", "general");   }   public Employee (name) {      this(name, "general");   }   public Employee (name, dept) {      this.name = name;      this.dept = dept;   }}
    function WorkerBee (projs) {    this.projects = projs || [];}WorkerBee.prototype = new Employee;
    public class WorkerBee extends Employee {   public String[] projects;   public WorkerBee () {      this(new String[0]);   }   public WorkerBee (String[] projs) {      this.projects = projs;   }}
    function Engineer (mach) {   this.dept = "engineering";   this.machine = mach || "";}Engineer.prototype = new WorkerBee;
    public class Engineer extends WorkerBee {   public String machine;   public WorkerBee () {      this.dept = "engineering";      this.machine = "";   }   public WorkerBee (mach) {      this.dept = "engineering";      this.machine = mach;   }}
     

    These JavaScript definitions use a special idiom for setting default values:

    this.name = name || "";

    The JavaScript logical OR operator (||) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.
    With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 5, you can use this statement to create a new Engineer:

    jane = new Engineer("belau");

    Jane's properties are now:

    jane.name == "";jane.dept == "general";jane.projects == [];jane.machine == "belau"

    Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.
    So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. Figure 6 shows these new definitions.
    Figure 6    Specifying properties in a constructor, take 2

    Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

    function Engineer (name, projs, mach) {    this.base = WorkerBee;    this.base(name, "engineering", projs);    this.projects = mach || "";}

    Assume we create a new Engineer object as follows:

    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");

    JavaScript follows these steps:

    1.   First, the new operator creates a generic object and sets its __proto__ property to Engineer.prototype.

    2.   The new operator then passes the new object to the Engineer constructor as the value of the this keyword.

    3.   Next, the constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.

    NOTE: The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.

    4.   Next, the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property and this value overrides the value inherited from Employee.

    5.   Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.

    6.   Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".

    7.   Upon return from the constructor, JavaScript assigns the new object to the jane variable.

    You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you've set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have these statements:

    function Engineer (name, projs, mach) {    this.base = WorkerBee;    this.base(name, "engineering", projs);    this.projects = mach || "";}jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");Employee.prototype.specialty = "none";

    The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

    function Engineer (name, projs, mach) {    this.base = WorkerBee;    this.base(name, "engineering", projs);    this.projects = mach || "";}Engineer.prototype = new WorkerBee;jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");Employee.prototype.specialty = "none";

    Now the value of the jane object's specialty property is "none".

    Property Inheritance Revisited

    The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties.

    Local versus Inherited Values

    Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:

    1. Check to see if the value exists locally. If it does, return that value.
    2. If there isn't a local value, check the prototype chain (using the __proto__ property).
    3. If an object in the prototype chain has a value for the specified property, return that value.
    4. If no such property is found, the object does not have the property.

    The outcome of this simple set of steps depends on how you've defined things along the way. In our original example, we had these definitions:

    function Employee () {    this.name = "";    this.dept = "general";}
    function WorkerBee () {    this.projects = [];}WorkerBee.prototype = new Employee;

    With these definitions, assume you create amy as an instance of WorkerBee with this statement:

    amy = new WorkerBee;

    The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

    amy.name == "";amy.dept = "general";amy.projects == [];

    Now assume you change the value of the name property in the prototype associated with Employee:

    Employee.prototype.name = "Unknown"

    At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.
    When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.
    If you want to change the value of an object property at runtime and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the code above to the following:

    function Employee () {   this.dept = "general";}Employee.prototype.name = "";
    function WorkerBee () {    this.projects = [];}WorkerBee.prototype = new Employee;
    amy = new WorkerBee;
    Employee.prototype.name = "Unknown";

    In this case, the name property of amy becomes "Unknown".
    As these examples show, if you want to have default values for object properties and you want to be able to change the default values at runtime, you should set the properties in the constructor's prototype, not in the constructor function itself.

    Determining Instance Relationships

    You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have an instanceof operator for this purpose. JavaScript does not provide instanceof, but you can write such a function yourself.
    As discussed in "Inheriting Properties", when you use the new operator with a constructor function to create a new object, JavaScript sets the __proto__ property of the new object to the value of the prototype property of the constructor function. You can use this to test the prototype chain.
    For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an __proto__ object as follows:

    chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");

    With this object, the following statements are all true:

    chris.__proto__ == Engineer.prototype;chris.__proto__.__proto__ == WorkerBee.prototype;chris.__proto__.__proto__.__proto__ == Employee.prototype;chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;

    Given this, you could write an instanceOf function as follows:

    function instanceOf(object, constructor) {    while (object != null) {       if (object == constructor.prototype)          return true;       object = object.__proto__;    }    return false; }

    With this definition, the following expressions are all true:

    instanceOf (chris, Engineer)instanceOf (chris, WorkerBee)instanceOf (chris, Employee)instanceOf (chris, Object)

    But this expression is false:

    instanceOf (chris, SalesPerson)

    Global Information in Constructors

    When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition for Employee:

    var idCounter = 1;
    function Employee (name, dept) {   this.name = name || "";   this.dept = dept || "general";   this.id = idCounter++;}

    With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:

    victoria = new Employee("Pigbert, Victoria", "pubs")harry = new Employee("Tschopik, Harry", "sales")

    victoria.id is 1 and harry.id is 2. At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy we've been working with, the Employee constructor is called every time we set up a prototype. That is, assume you have this code:

    var idCounter = 1;
    function Employee (name, dept) {   this.name = name || "";   this.dept = dept || "general";   this.id = idCounter++;}
    function Manager (name, dept, reports) {...}Manager.prototype = new Employee;
    function WorkerBee (name, dept, projs) {...}WorkerBee.prototype = new Employee;
    function Engineer (name, projs, mach) {...}Engineer.prototype = new WorkerBee;
    function SalesPerson (name, projs, quota) {...}SalesPerson.prototype = new WorkerBee;
    mac = new Engineer("Wood, Mac");

    Further assume that the definitions we've omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.
    Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using this constructor:

    function Employee (name, dept) {   this.name = name || "";   this.dept = dept || "general";   if (name)      this.id = idCounter++;}

    When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In our example, mac.id would be 1.

    No Multiple Inheritance

    Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.
    As we've already said, inheritance of property values occurs at runtime by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.
    In JavaScript you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

    function Hobbyist (hobby) {   this.hobby = hobby || "scuba";}
    function Engineer (name, projs, mach, hobby) {   this.base1 = WorkerBee;   this.base1(name, "engineering", projs);   this.base2 = Hobbyist;   this.base2(hobby);   this.projects = mach || "";}Engineer.prototype = new WorkerBee;
    dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")

    Further assume that the definition of WorkerBee is as we've previously seen it. In this case, the dennis object has these properties:

    dennis.name == "Doe, Dennis"dennis.dept == "engineering"dennis.projects == ["collabra"]dennis.machine == "hugo"dennis.hobby == "scuba"

    So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

    Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]

    The dennis object does not inherit this new property.

(转)java关于23种java关于23种设计模式的有趣见解 设计模式的有趣见解相关推荐

  1. 神仙程序媛小姐姐的23个Java设计模式 ,全站式保姆的Java教程导航帖(已完结)

    Java的23个Java设计模式 ,已完结,以后的时间不定期补番.还有一些了解即可,不需要使用,现实开发用不掉 之前,分多篇讲解Java23种设计模式,毕竟太散,现将全部内容进行汇总.大家以后学习23 ...

  2. 打包编译 Error:(23,34) java: 找不到符号符号:类 xxx位置:程序包 xxx.xxx

    打war包 Error:(23,34) java: 1. clean + package 轻度患者 2. clean + install + package 重度患者 3. file-setting- ...

  3. Java 8 获取某天最大(23:59:59)最小(00:00:00)时间

    Java 8 中获取某一天最大时间和最小时间如下: import java.text.SimpleDateFormat; import java.time.Instant; import java.t ...

  4. spark集群环境下Lost task 0.0 in stage 10.0 (TID 17, 10.28.23.202): java.io.FileNotFoundException

    spark从当前目录加载文件报错,Lost task 0.0 in stage 10.0 (TID 17, 10.28.23.202): java.io.FileNotFoundException,明 ...

  5. 新来的23岁Java开发上来秀了波操作,真的是扮猪吃老虎

    咋这快过年了还有人来面试的,一看简历,嘿?23岁,这不刚毕业的小毛孩子嘛,结果没想到人家上来就把现有项目的性能优化了一遍,给公司节省了一半的成本,这种"王炸"打法,直接给所有人整懵 ...

  6. 杀手级AI补代码工具问世,支持23种语言、5种主流编辑器!(附链接)

    本文经AI新媒体量子位授权转载,转载请联系出处. 本文约2100字,建议阅读10分钟. 本文介绍了新开发出的"Deep TabNine"代码补全工具,支持多种编程语言和编辑器. G ...

  7. 杀手级AI补代码工具问世,支持23种语言及5种主流编辑器,程序员沸腾了

    边策 安妮 发自 凹非寺 量子位 出品 | 公众号 QbitAI GPT-2,一个来自OpenAI的逆天语言模型,现在能用来补全代码了. 一位来自加拿大的大四学霸,开发了一款"Deep Ta ...

  8. java笔记--关于线程同步(7种同步方式)

    关于线程同步(7种方式) --如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3897440.html"谢谢-- 为何要使用同步? ...

  9. 面试题:四种Java线程池用法解析 !=!=未看

    1.new Thread的弊端 执行一个异步任务你还只是如下new Thread吗? 1 2 3 4 5 6 7 8 new Thread(new Runnable() {   @Override   ...

  10. Java中List for循环的6种写法总结(推荐)(亲测)

    如下所示: List<String> list = new ArrayList<String>(); ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...

最新文章

  1. React 开发环境搭建
  2. 用GAN来做图像生成,这是最好的方法
  3. sigsuspend的理解
  4. python画二维散点图-python3实现绘制二维点图
  5. “无中生有”计算机视觉探奇
  6. LaTeX配置及实用工具汇总
  7. 蓝桥杯-字串统计(java)
  8. HttpClient的几个实现类
  9. Mask R-CNN抢车位,快人一步!
  10. Windows下git安装及使用技巧
  11. Framework学习(二)Android的启动过程
  12. BP神经网络用于预测
  13. 自动计数报警器c语言程序,自动计数报警器.ppt
  14. 地级市交通基础设施数据,省份交通基础设施数据,处理好的面板数据(excel或stata版本)
  15. 编译器-有限自动机和正则表达式
  16. web技术基础---网站设计说明书
  17. 人脸识别“抓”错了人,他在监狱待了10天
  18. Linux知识点概要之课堂总结
  19. 美通社企业新闻汇总 | 2019.1.29 | 华为四款明星产品亮相世界移动通信大会;一季度全球智能手机同比将减产10%...
  20. 基于Python实现的英文文本信息检索系统

热门文章

  1. SqlConnection对象和using本质, ExecuteScalar和ExecuteReader的区别
  2. U盘文件被格式化如何恢复
  3. 逆天者的java版屏幕准星
  4. 虎头虎脑的sizeof、strlen、数组长度、数组中元素个数和字符串长度
  5. python画五角星没有填色_pycharm运行画五角星程序后,出不来图形
  6. 飞凡汽车,你拿什么和人斗?
  7. win10安装MySQL步骤与问题解决方法
  8. 国税增值税发票验证码自动识别
  9. EF的TransactionScope
  10. python 字符串详解(附案例)