JAVA学习点点滴滴

用开放的脑子去闯荡;用开阔的视野去拼搏;用平和的身心去磨练;用美好的理想去追求!

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  18 随笔 :: 1 文章 :: 2 评论 :: 0 Trackbacks

2006年2月22日 #

创建型模式

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 海思 阅读(249) | 评论 (0)编辑 收藏

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:

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.

    Last Updated: 12/18/97 15:19:54


    Copyright © 1997 Netscape Communications Corporation

  • posted @ 2007-01-21 16:19 海思 阅读(463) | 评论 (0)编辑 收藏

    跨越边界: JavaScript 语言特性

    研究编程语言中的“丑小鸭”

    developerWorks
    文档选项
    将此页作为电子邮件发送

    将此页作为电子邮件发送

    未显示需要 JavaScript 的文档选项

    样例代码


    拓展 Tomcat 应用

    下载 IBM 开源 J2EE 应用服务器 WAS CE 新版本 V1.1


    级别: 初级

    Bruce Tate (bruce.tate@j2life.com), 总裁, RapidRed

    2007 年 1 月 18 日

    JavaScript 常被人们认为是编程语言中无足轻重的一员。这种观点的形成可以“归功”于其开发工具、复杂且不一致的面向 HTML 页面的文档对象模型以及不一致的浏览器实现。但 JavaScript 绝对不仅仅是一个玩具这么简单。在本文中,Bruce Tate 向您介绍了 JavaScript 的语言特性。

    几乎每个 Web 开发人员都曾有过诅咒 JavaScript 的经历。这个备受争议的语言受累于其复杂的称为文档对象模型 (DOM)的编程模型、糟糕的实现和调试工具以及不一致的浏览器实现。直到最近,很多开发人员还认为 Javascript 从最好的方面说是无可避免之灾祸,从最坏的方面说不过是一种玩具罢了。

    然而 JavaScript 现在开始日益重要起来,而且成为了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏使一些业界领袖人物也不得不开始重新审视这种编程语言。诸如 Ajax (Asynchronous JavaScript + XML) 这样的编程技术让 Web 网页更加迷人。而完整的 Web 开发框架,比如 Apache Cocoon,则让 JavaScript 的应用越来越多,使其不只限于是一种用于制作 Web 页面的简单脚本。JavaScript 的一种称为 ActionScript 的派生物也推动了 Macromedia 的 Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino 让 JavaScript 成为了 Java™ 开发人员所首选的一类脚本语言(参见 参考资料)。

    我的好友兼同事 Stuart Halloway 是 Ajax 方面的专家,曾在其教授的 JavaScript 课程中做过这样的开场白:“到 2011 年,JavaScript 将被公认为是一种拥有开发现代应用程序所需的一整套新特性的语言” 。他继而介绍说 JavaScript 程序要比类似的 Java 程序紧密十倍,并继续展示了使其之所以如此的一些语言特性。

    关于这个系列

    跨越边界系列中,作者 Bruce Tate 提出了这样一个主张:今天的 Java 程序员通过学习其他技术和语言,会得到很好的帮助。编程领域已经发生了变化,Java 技术不再是所有开发项目理所当然的最佳选择。其他框架正在影响 Java 框架构建的方式,而从其他语言学到的概念也有助于 Java 编程。对 Python(或 Ruby、Smalltalk 等等)代码的编写可能改变 Java 编码的方式。

    这个系列介绍的编程概念和技术,与 Java 开发有根本的不同,但可以直接应用于 Java 编程。在某些情况下,需要集成这些技术来利用它们。在其他情况下,可以直接应用这些概念。单独的工具并不重要,重要的是其他语言和框架可以影响 Java 社区中的开发人员、框架,甚至是基本方式。

    在这篇文章中,我将带您探究 JavaScript 的一些特性,看看这些特性如何让它如此具有吸引力:

    • 高阶函数: 一个高阶函数可以将函数作为参数,也可以返回一个函数。此特性让 JavaScript 程序员可以用 Java 语言所不能提供的方法来操纵函数。

    • 动态类型:通过延迟绑定,JavaScript 可以更准确和更灵活。

    • 灵活的对象模型:JavaScript 的对象模型使用一种相对不常见的方式进行继承 —— 称为原型 —— 而不是 Java 语言中更常见的基于类的对象模型。

    您可能已经熟悉动态类型模型、高阶函数形式的函数式编程以及开放对象模型这些概念,因为我在其他的跨越边界 系列文章中已经作过相关的介绍。如果您从未进行过任何正式的 JavaScript 开发,您很可能会认为这些特性属于非常复杂的语言,例如 Python、Lisp、Smalltalk 和 Haskell,而绝非像 JavaScript 这样的语言所能提供的。因此,我将用实际的代码示例来说明这些概念。

    立即开始

    您无需设置 JavaScript。如果您可以在浏览器中阅读此篇文章,就证明您已经准备就绪了。本文包含的所有编程示例都可以在大多数浏览器内运行。我使用的是 Firefox。

    用在 <script type='text/javascript'></script> 标记之间所包含的 JavaScript 加载简单的 Web 页面。清单 1 可以显示 Hello, World 文本:



    清单 1. Hello, world
    				
    <script type='text/javascript'>
    alert('Hello, World.')
    </script>
    

    要运行此代码,只需创建一个名为 example1.html 的文件。将清单 1 的代码复制到该文件内,并在浏览器中加载此文件(参看 下载 部分以获得本文使用的所有示例 HTML 文件)。注意到每次重载此页面时,该代码都会立即执行。

    alert 是个函数调用,只有一个字符串作为参数。图 1 显示了由清单 1 中的代码弹出的警告框,显示文本 “Hello, World”。如果代码在 HTML body 之内(目前并未指定任何 body,但浏览器能接受不规则的 HTML,并且整个页面都默然作为一个 body 被处理)。页面一旦加载,JavaScript 就会立即执行。



    图 1. Hello, world
    Hello, World.

    如果要延迟执行,可以在 HTML <head> 元素声明 JavaScript 函数,如清单 2 所示:



    清单 2. 延迟执行
    				
    <head>
        
        <script type='text/javascript'>
            function hello() {
                alert('Hello, World.')
            }
        </script>
    </head>
    <body>
        <button onclick="hello();">Say Hello</button>
    </body>
    

    将清单 2 中的代码输入到一个 HTML 文件,在浏览器内加载该文件,单击 Say Hello 按钮,结果如图 2 所示:



    图 2. 延迟执行
    延迟执行




    回页首


    高阶函数

    清单 2,可以大致体会到一些 JavaScript 在操纵函数方面的能力。将函数名称传递给 HTML button 标记并利用 HTML 的内置事件模型。使用 JavaScript 时,我会经常在变量或数组中存储函数(在本文后面的 对象模型 一节,您会看到 JavaScript 对象模型策略大量使用了此技巧)。例如,查看一下清单 3:



    清单 3. 用变量操纵函数
    				
    <head>
        
        <script type='text/javascript'>
            hot = function hot() {
                alert('Sweat.')
            }
            cold  = function cold() {
                alert('Shiver.')
            }
            
            function swap() {
                temp = hot
                hot = cold
                cold = temp    
                alert('Swapped.')
            }
        </script>
    </head>
    <body>
        <button onclick="hot();">Hot</button>
        <button onclick="cold();">Cold</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    函数是 JavaScript 中的一类对象,可以自由地操纵它们。首先我声明两个函数:hotcold。并分别在不同的变量存储它们。单击 Hot 或 Cold 按钮会调用对应的函数,生成一个告警。接下来,声明另一个函数用来交换 Hot 和 Cold 按钮的值,将此函数与第三个按钮关联,该按钮显示如图 3 所示的告警:



    图 3. 操纵函数

    这个例子说明可以像处理其他变量一样处理函数。C 开发人员很容易将此概念看作是函数指针 功能,但 JavaScript 的高阶函数的功能更为强大。该特性让 JavaScript 程序员能够像处理其他变量类型一样轻松处理动作或函数。

    将函数用作函数的参数,或将函数作为值返回,这些概念属于高阶函数的领域。清单 4 对 清单 3 做了一点点修改,显示了能返回函数的高阶函数:



    清单 4. 高阶函数
    				
    <head>
    
        <script type='text/javascript'>
    
            function temperature() {
                return current
            }
    
            hot = function hot() {
                alert('Hot.')
            }
    
            cold  = function cold() {
                alert('Cold.')
            }
    
            current = hot
    
            function swap() {
                if(current == hot) {
                  current = cold
                } else {
                  current = hot
                }
            }
        </script>
    </head>
    <body>
        <button onclick="funct = temperature()();">Temperature</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    这个例子解决了一个常见问题:如何将更改中的行为附加到用户接口事件?通过高阶函数,这很容易做到。temperature 高阶函数返回 current 的值,而 current 又可以有 hotcold 函数。看一下这个有些陈旧的函数调用:temperature()()。第一组括号用于调用 temperature 函数。第二组括号调用由 temperature返回 的函数。图 4 显示了输出:



    图 4. 高阶函数
    高阶函数

    高阶函数是函数式编程的基础,对比面向对象编程,函数式编程代表了更高级别的抽象。但 JavaScript 的实力并不仅限于高阶函数。JavaScript 的动态类型就极为适合 UI 开发。





    回页首


    动态类型

    通过静态类型,编译器可以检查参数和变量的值或针对一个给定操作所允许的返回值。其优势是编译器可以做额外的错误检查。而且静态类型还可以为诸如 IDE 这样的工具提供更多信息,带来其他一些特性,比如更好的代码完成功能。但静态类型也存在着如下一些劣势:

    • 必须提前声明意图,这常常会导致灵活性降低。例如,更改一个 Java 类就会更改类的类型,因而必须重新编译。对比之下,Ruby 允许开放的类,但更改一个 Java 类还是会更改类的类型。

    • 要实现相同的功能,必须输入更多的代码。例如,必须用参数形式包括进类型信息,必须用函数形式返回值和所有变量的类型。另外,还必须声明所有变量并显式地转化类型。

    • 静态语言的编译-部署周期要比动态语言的部署周期长,尽管一些工具可被用来在某种程度上缓解这一问题。

    静态类型更适合用于构建中间件或操作系统的语言中。UI 开发常常需要更高的效率和灵活性,所以更适合采用动态类型。我深知这种做法存在危险。相信使用过 JavaScript 的 Web 开发人员都曾经为编译器本应检测到的错误类型的变量而绞尽脑汁。但它所带来的优势同样不可否认。下面将举例加以说明。

    首先,考虑一个对象的情况。在清单 5 中,创建一个新对象,并访问一个不存在的属性,名为 color



    清单 5. 引入一个属性
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = 'blue'
        alert('The color is ' + blank_object.color)
    </script>
    

    当加载并执行此应用程序时,会得到如图 5 所示的结果:



    图 5. 引入属性
     引入属性

    JavaScript 并不会报告 blue 属性不存在的错误。静态类型的拥护者大都会被本例所吓倒,因为本例中的错误被很好地隐匿了。虽然这种做法多少会让您感觉有些不正当,但您也不能否认它巨大的诱惑力。您可以很快引入属性。如果将本例和本文之前的例子结合起来,还可以引入行为。记住,变量可以保存函数!所以,基于动态类型和高阶函数,您可以在任何时候向类中引入任意的行为。

    可以轻松地重写 清单 5,使其如清单 6 所示:



    清单 6. 引入行为
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = function() { return 'blue'}
        alert('The color is ' + blank_object.color())
    </script>
    

    从上例可以看出,在 JavaScript 的不同概念之间可以如此轻松地来回变换,其含义上的变化很大 —— 比如,是引入行为还是引入数据 —— 但语法上的变化却很小。该语言很好的延展性是它的一种优势,但同样也是其缺点所在。实际上,该语言本身的对象模型就是 JavaScript 延展程度的一种体现。





    回页首


    对象模型

    到目前为止,您应该对 JavaScript 有一个正确的评价了,它绝非只如一个玩具那么简单。事实上,很多人都使用过其对象模型创建过极为复杂、设计良好的面向对象软件。但对象模型尤其是用于继承的对象模型又非您一贯认为的那样。

    Java 语言是基于类的。当构建应用程序时,也同时构建了可以作为所有对象的模板的新类。然后调用 new 来实例化该模板,创建一个新对象。而在 JavaScript 中,所创建的是一个原型,此原型是一个实例,可以创建所有未来的对象。

    现在先暂且放下这些抽象的概念,去查看一些实际代码。比如,清单 7 创建了一个简单的 Animal,它具有 name 属性和 speak 动作。其他动物会从这个基础继承。



    清单 7. 创建一个构造函数
    				
    <script type='text/javascript'>        
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    
    myAnimal = new Animal();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
    
    </script>
    

    清单 7 的结果如图 6 所示:



    图 6. 创建一个构造函数
    构造函数

    对于 Java 开发人员而言,清单 7 中的代码看起来多少有点生疏和奇怪。实际上对于没有亲自构建过对象的许多 JavaScript 开发人员来说,这些代码同样看起来有点生疏和奇怪。也许,下面的解释可以让大家能够更好地理解这段代码。

    实际上,您只需重点关注其中三段信息。首先,JavaScript 用嵌套函数表示对象。这意味着清单 7 中的 Animal 的定义是一种有效的语法。第二,JavaScript 基于原型或现有的对象的实例来构造对象,而非基于类模板。funct() 是一种调用,但 new Animal() 却基于 Animal 内的原型构造一个对象。最后,在 JavaScript 中,对象只是函数和变量的集合。每个对象并不与类型相关,所以可以自由地修改这种结构。

    回到 清单 7。如您所见,JavaScript 基于在 Animal 中指定的原型定义一个新对象:myAnimal。继而可以使用原型中的属性和函数,甚或重定义函数和属性。这种灵活性可能会让 Java 开发人员受不了,因为他们不习惯这种行为,但它的确是一种十分强大的模型。

    现在我还要更深入一步。您还可以使用名为 prototype 实例变量来指定对象的基础。方法是设置 prototype 实例变量使其指向继承链的父。如此设置 prototype 之后,您所创建的对象会为未指定的那些对象继承属性和函数。这样一来,您就可以模仿面向对象的继承概念。以清单 8 为例:



    清单 8. 通过原型继承
    				
    <script type='text/javascript'>        
    
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    Dog = function() {
      this.speak = function() {
        return "Woof!"
      }
    }
    Dog.prototype = new Animal();
    
    myAnimal = new Dog();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
          </script>
    

    在清单 8 中,创建了一个 Dog 原型。此原型基于 AnimalDog 重定义 speak() 方法但却不会对 name() 方法做任何改动。随后,将原型 Dog 设置成 Animal。图 7 显示了其结果:



    图 7. 通过原型继承
    继承

    这也展示了 JavaScript 是如何解决到属性或方法的引用问题的:

    • JavaScript 基于原始的原型创建实例,该原型在构造函数中定义。任何对方法或属性的引用都会使用所生成的原始副本。

    • 您可以在对象内像定义其他任何变量一样重新定义这些变量。这样做必然会更改此对象。所以您显式定义的任何属性或函数都将比在原始的原型中定义的那些属性或函数优先级要高。

    • 如果您显式设置了名为 prototype 的实例变量,JavaScript 就会在此实例中寻找任何未定义的实例变量或属性。这种查找是递归的:如果 在 prototype 内定义的实例不能找到属性或函数,它就会在 原型中查找,依此类推。

    那么,JavaScript 的继承模型到底是什么样的?这取决于您如何对它进行定义。您需要定义继承行为以便可以覆盖它。然而,从本质上讲,JavaScript 更像是一种函数式语言,而非面向对象的语言,它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极为灵活、开放和强大,具有全部的反射性。有些人可能会说它太过灵活。而我的忠告则是,按具体作业的需要选择合适的工具。





    回页首


    结束语

    JavaScript 对象模型构建在该语言的其他功能之上来支持大量的库,比如 Dojo(参见 参考资料)。这种灵活性让每个框架能够以一种精细的方式更改对象模型。在某种程度上,这种灵活性是一种极大的缺点。它可以导致可怕的互操作性问题(尽管该语言的灵活性可以部分缓解这些问题)。

    而另一方面,灵活性又是一种巨大的优势。Java 语言一直苦于无法充分增强其灵活性,原因是它的基本对象模型还未灵活到可以被扩展的程度。一个典型的企业级开发人员为能够成功使用 Java 语言必须要学习很多东西,而新出现的一些优秀的开放源码项目和新技术,比如面向方面编程、Spring 编程框架和字节码增强库,则带来了大量要学的代码。

    最后,JavaScript 优秀的灵活性的确让您体会到了一些高阶语言的强大功能。当然您无需选择为每个项目或大多数项目都做这样的权衡和折衷。但了解一种语言的优势和劣势 —— 通过参考大量信息,而不仅仅基于广告宣传或公众意见 —— 会让您可以更好地控制何时需要使用以及何时不能使用这种语言。当您在修改 JavaScript Web 小部件时,您至少知道该如何让此语言发挥它最大的优势。请继续跨越边界吧。


    参考资料

    学习
    posted @ 2007-01-21 15:49 海思 阅读(219) | 评论 (0)编辑 收藏

    1、取出刚刚插入(删除)的数据SELECT 字段名 FROM INSERTED(DELETED)
    2、对于UPDATE实际上是先DELETE然后再INSERT所以如果想得到UPDATE前后的数据值,应该先从DELETED取出,然后从INSERTED取出;
    3、IF UPDATE(列名)可以判断更新或插入哪一个字段的值;
    4、@@ROWCOUNT可以判断上一行查询操作得到的列数;
    5、给变量赋值用SET @ZQB = 13;
    6、察看是否有符合条件的记录IF EXISTS (SELECT name FROM sysobjects WHERE name = 'reminder' AND type = 'TR');
    7、定义游标,如下:
    DECLARE c1 CURSOR FOR
    SELECT emp_mgr.emp
    FROM emp_mgr, inserted
    WHERE emp_mgr.emp = inserted.mgr

    OPEN c1
    FETCH NEXT FROM c1 INTO @e--从游标中取出数据
    WHILE @@fetch_status = 0--判断是否到最后
    BEGIN
    UPDATE emp_mgr
    SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Add 1 for newly
    WHERE emp_mgr.emp = @e -- added employee.

    FETCH NEXT FROM c1 INTO @e
    END
    CLOSE c1
    DEALLOCATE c1--删除游标引用

    posted @ 2007-01-07 14:34 海思 阅读(203) | 评论 (0)编辑 收藏

    matrixeditor 发表于 2005-07-28 11:06:41
    作者:Matrixeditor     来源:BEA dev2dev
    评论数:4 点击数:6,815     投票总得分:8 投票总人次:3
    关键字:

    摘要:

    Acegi安全系统,是一个用于Spring Framework的安全框架,能够和目前流行的Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean Context,拦截器和面向接口的编程方式。因此,Acegi安全系统能够轻松地适用于复杂的安全需求。
               Acegi安全系统,是一个用于Spring Framework的安全框架,能够和目前流行的Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean Context,拦截器和面向接口的编程方式。因此,Acegi安全系统能够轻松地适用于复杂的安全需求。
           安全涉及到两个不同的概念,认证和授权。前者是关于确认用户是否确实是他们所宣称的身份。授权则是关于确认用户是否有允许执行一个特定的操作。
           在Acegi安全系统中,需要被认证的用户,系统或代理称为"Principal"。Acegi安全系统和其他的安全系统不同,它并没有角色和用户组的概念。
    Acegi系统设计
      关键组件
          Acegi安全系统包含以下七个关键的功能组件:
            1 Authentication对象,包含了Principal,Credential和Principal的授权信息。同时还可以包含关于发起认证请求的客户的其他信息,如IP地址。
            2 ContextHolder对象,使用ThreadLocal储存Authentication对象的地方。
            3 AuthenticationManager,用于认证ContextHolder中的Authentication对象。
            4 AccessDecissionManager,用于授权一个特定的操作。
            5 RunAsManager,当执行特定的操作时,用于选择性地替换Authentication对象。
            6 Secure Object拦截器,用于协调AuthenticationManager,AccessDecissionManager,RunAsManager和特定操作的执行。
            7 ObjectDefinitionSource,包含了特定操作的授权定义。
          这七个关键的功能组件的关系如下图所示(图中灰色部分是关键组件):


    安全管理对象
           Acegi安全系统目前支持两类安全管理对象。
           第一类的安全管理对象管理AOP Alliance的MethodInvocation,开发人员可以用它来保护Spring容器中的业务对象。为了使Spring管理的Bean可以作为MethodInvocation来使用,Bean可以通过ProxyFactoryBean和BeanNameAutoProxyCreator来管理,就像在Spring的事务管理一样使用。
           第二类是FilterInvocation。它用过滤器(Filter)来创建,并简单地包装了HTTP的ServletRequest,ServletResponse和FilterChain。FilterInvocation可以用来保护HTTP资源。通常,开发人员并不需要了解它的工作机制,因为他们只需要将Filter加入web.xml,Acegi安全系统就可以工作了。

    安全配置参数
           每个安全管理对象都可以描述数量不限的各种安全认证请求。例如,MethodInvocation对象可以描述带有任意参数的任意方法的调用,而FilterInvocation可以描述任意的HTTP URL。
           Acegi安全系统需要记录应用于每个认证请求的安全配置参数。例如,对于BankManager.getBalance(int accountNumber)方法和BankManager.approveLoan(int applicationNumber)方法,它们需要的认证请求的安全配置很不相同。
           为了保存不同的认证请求的安全配置,需要使用配置参数。从实现的视角来看,配置参数使用ConfigAttribute接口来表示。Acegi安全系统提供了ConfigAttribute接口的一个实现,SecurityConfig,它把配置参数保存为一个字符串。
           ConfigAttributeDefinition类是ConfigAttribute对象的一个简单的容器,它保存了和特定请求相关的ConfigAttribute的集合。
           当安全拦截器收到一个安全认证请求时,需要决定应用哪一个配置参数。换句话说,它需要找出应用于这个请求的ConfigAttributeDefinition对象。这个查找的过程是由ObjectDefinitionSource接口来处理的。这个接口的主要方法是public ConfigAttributeDefinition getAttributes(Object object),其中Object参数是一个安全管理对象。因为安全管理对象包含有认证请求的详细信息,所以ObjectDefinitionSource接口的实现类可以从中获得所需的详细信息,以查找相关的ConfigAttributeDefiniton对象。


    Acegi如何工作
           为了说明Acegi安全系统如何工作,我们设想一个使用Acegi的例子。通常,一个安全系统需要发挥作用,它必须完成以下的工作:
          1 首先,系统从客户端请求中获得Principal和Credential;
          2 然后系统认证Principal和Credential信息;
          3 如果认证通过,系统取出Principal的授权信息;
          4 接下来,客户端发起操作请求;
          5 系统根据预先配置的参数检查Principal对于该操作的授权;
          6 如果授权检查通过则执行操作,否则拒绝。
          那么,Acegi安全系统是如何完成这些工作的呢?首先,我们来看看Acegi安全系统的认证和授权的相关类:
          安全拦截器的抽象基类,它包含有两个管理类,AuthenticationManager和AccessDecisionManager。AuthenticationManager用于认证ContextHolder中的Authentication对象(包含了Principal,Credential和Principal的授权信息);AccessDecissionManager则用于授权一个特定的操作。

          下面来看一个MethodSecurityInterceptor的例子:
          <bean id="bankManagerSecurity" 
                         class="net.sf.acegisecurity.intercept.method.MethodSecurityInterceptor">
                 <property name="validateConfigAttributes">
                        <value>true</value>
                </property>
                <property name="authenticationManager">
                       <ref bean="authenticationManager"/>
                </property>
                <property name="accessDecisionManager">
                      <ref bean="accessDecisionManager"/>
                </property>
                <property name="objectDefinitionSource">
                      <value>
                         net.sf.acegisecurity.context.BankManager.delete*=
                                 ROLE_SUPERVISOR,RUN_AS_SERVER
                         net.sf.acegisecurity.context.BankManager.getBalance=
                                 ROLE_TELLER,ROLE_SUPERVISOR,BANKSECURITY_CUSTOMER,RUN_
                      </value>
                </property>
          </bean>

          上面的配置文件中,MethodSecurityInterceptor是AbstractSecurityInterceptor的一个实现类。它包含了两个管理器,authenticationManager和accessDecisionManager。这两者的配置如下:
          
    <bean id="authenticationDao" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
                   <property name="dataSource"><ref bean="dataSource"/></property>
          </bean>
          <bean id="daoAuthenticationProvider"
                         class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
                   <property name="authenticationDao"><ref bean="authenticationDao"/></property>
          </bean>
          <bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
                   <property name="providers">
                          <list><ref bean="daoAuthenticationProvider"/></list>
                   </property>
          </bean>
          <bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>
          <bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
                   <property name="allowIfAllAbstainDecisions"><value>false</value></property>
                   <property name="decisionVoters">
                          <list><ref bean="roleVoter"/></list>
                   </property>
          </bean>


           准备工作做好了,现在我们来看看Acegi安全系统是如何实现认证和授权机制的。以使用HTTP BASIC认证的应用为例子,它包括下面的步骤:
           1. 用户登录系统,Acegi从acegisecurity.ui子系统的安全拦截器(如BasicProcessingFilter)中得到用户的登录信息(包括Principal和Credential)并放入Authentication对象,并保存在ContextHolder对象中;
           2. 安全拦截器将Authentication对象交给AuthenticationManager进行身份认证,如果认证通过,返回带有Principal授权信息的Authentication对象。此时ContextHolder对象的Authentication对象已拥有Principal的详细信息;
           3. 用户登录成功后,继续进行业务操作;
           4. 安全拦截器(bankManagerSecurity)收到客户端操作请求后,将操作请求的数据包装成安全管理对象(FilterInvocation或MethodInvocation对象);
           5. 然后,从配置文件(ObjectDefinitionSource)中读出相关的安全配置参数ConfigAttributeDefinition;
           6. 接着,安全拦截器取出ContextHolder中的Authentication对象,把它传递给AuthenticationManager进行身份认证,并用返回值更新ContextHolder的Authentication对象;
           7. 将Authentication对象,ConfigAttributeDefinition对象和安全管理对象(secure Object)交给AccessDecisionManager,检查Principal的操作授权;
           8. 如果授权检查通过则执行客户端请求的操作,否则拒绝;

    AccessDecisionVoter
           注意上节的accessDecisionManager是一个AffirmativeBased类,它对于用户授权的投票策略是,只要通过其中的一个授权投票检查,即可通过;它的allowIfAllAbstainDecisions属性值是false,意思是如果所有的授权投票是都是弃权,则通不过授权检查。
           Acegi安全系统包括了几个基于投票策略的AccessDecisionManager,上节的RoleVoter就是其中的一个投票策略实现,它是AccessDecisionVoter的一个子类。AccessDecisionVoter的具体实现类通过投票来进行授权决策,AccessDecisionManager则根据投票结果来决定是通过授权检查,还是抛出AccessDeniedException例外。
           AccessDecisionVoter接口共有三个方法:
    public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config);
    public boolean supports(ConfigAttribute attribute);
    public boolean supports(Class clazz);
           其中的vote方法返回int返回值,它们是AccessDecisionVoter的三个静态成员属性:ACCESS_ABSTAIN,,ACCESS_DENIED和ACCESS_GRANTED,它们分别是弃权,否决和赞成。
           Acegi安全系统中,使用投票策略的AccessDecisionManager共有三个具体实现类:AffirmativeBased、ConsensusBased和UnanimousBased。它们的投票策略是,AffirmativeBased类只需有一个投票赞成即可通过;ConsensusBased类需要大多数投票赞成即可通过;而UnanimousBased类需要所有的投票赞成才能通过。
           RoleVoter类是一个Acegi安全系统AccessDecisionVoter接口的实现。如果ConfigAttribute以ROLE_开头,RoleVoter则进行投票。如果GrantedAuthority的getAutority方法的String返回值匹配一个或多个以ROLE_开头的ConfigAttribute,则投票通过,否则不通过。如果没有以ROLE_开头的ConfigAttribute,RoleVoter则弃权。

    安全拦截器
      拦截器如何工作
      MethodInvocation拦截器
      FilterInvocation拦截器
    认证
      认证请求
      认证管理器
      Authentication Provider
    授权
      Access Decision Manager
      Voting Decision Manager
      授权管理推荐
    ContextHolder的用户接口
      用户接口目标
      HTTP会话认证
      HTTP Basic认证

    1、Log4j的概念
       Log4j中有三个主要的组件,它们分别是Logger、Appender和Layout,Log4j 允许开发人员定义多个Logger,每个Logger拥有自己的名字,Logger之间通过名字来表明隶属关系。有一个Logger称为Root,它永远 存在,且不能通过名字检索或引用,可以通过Logger.getRootLogger()方法获得,其它Logger通过 Logger.getLogger(String name)方法。
       Appender则是用来指明将所有的log信息存放到什么地方,Log4j中支持多种appender,如 console、files、GUI components、NT Event Loggers等,一个Logger可以拥有多个Appender,也就是你既可以将Log信息输出到屏幕,同时存储到一个文件中。
       Layout的作用是控制Log信息的输出方式,也就是格式化输出的信息。
       Log4j中将要输出的Log信息定义了5种级别,依次为DEBUG、INFO、WARN、ERROR和FATAL,当输出时,只有级别高过配置中规定的 级别的信息才能真正的输出,这样就很方便的来配置不同情况下要输出的内容,而不需要更改代码,这点实在是方便啊。

    2、Log4j的配置文件
      虽然可以不用配置文件,而在程序中实现配置,但这种方法在如今的系统开发中显然是不可取的,能采用配置文件的地方一定一定要用配置文件。Log4j支持两 种格式的配置文件:XML格式和Java的property格式,本人更喜欢后者,首先看一个简单的例子吧,如下:

     log4j.rootLogger=debug, stdout, R
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

      # Pattern to output the caller's file name and line number.
      log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

      log4j.appender.R=org.apache.log4j.RollingFileAppender
      log4j.appender.R.File=example.log
      log4j.appender.R.MaxFileSize=100KB

      # Keep one backup file
      log4j.appender.R.MaxBackupIndex=1

      log4j.appender.R.layout=org.apache.log4j.PatternLayout
      log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
            

      首先,是设置root,格式为 log4j.rootLogger=[level],appenderName, ...,其中level就是设置需要输出信息的级别,后面是appender的输出的目的地,appenderName就是指定日志信息输出到哪个地方。您可以同时指定多个输出目的地。配置日志信息输出目的地Appender,其语法为
      log4j.appender.appenderName = fully.qualified.name.of.appender.class
      log4j.appender.appenderName.option1 = value1
      ...
      log4j.appender.appenderName.option = valueN
    Log4j提供的appender有以下几种:
      org.apache.log4j.ConsoleAppender(控制台)
      org.apache.log4j.FileAppender(文件)
      org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
      org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生新文件)
      org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
    配置日志信息的格式(布局),其语法为:
      log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class
      log4j.appender.appenderName.layout.option1 = value1
      ....
      log4j.appender.appenderName.layout.option = valueN
    Log4j提供的layout有以下几种:
      org.apache.log4j.HTMLLayout(以HTML表格形式布局),
      org.apache.log4j.PatternLayout(可以灵活地指定布局模式),
      org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串),
      org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)

    3、Log4j在程序中的使用
      要在自己的类中使用Log4j,首先声明一个静态变量Logger logger=Logger.getLog("classname");在使用之前,用PropertyConfigurator.configure ("配置文件")配置一下,现在就可以使用了,用法如下:logger.debug("debug message")或者logger.info("info message"),看下面一个小例子:

     import com.foo.Bar;
      import org.apache.log4j.Logger;
      import org.apache.log4j.PropertyConfigurator;
      public class MyApp {
        static Logger logger = Logger.getLogger(MyApp.class.getName());
        public static void main(String[] args) {
          // BasicConfigurator replaced with PropertyConfigurator.
          PropertyConfigurator.configure(args[0]);
          logger.info("Entering application.");
          Bar bar = new Bar();
          bar.doIt();
          logger.info("Exiting application.");
        }
      }



    [简介]

    对于一个典型的Web应用,完善的认证和授权机制是必不可少的,在SpringFramework中,Juergen Hoeller提供的范例JPetStore给了一些这方面的介绍,但还远远不够,Acegi是一个专门为SpringFramework提供安全机制的 项目,全称为Acegi Security System for Spring,当前版本为0.5.1,就其目前提供的功能,应该可以满足绝大多数应用的需求。

    本文的主要目的是希望能够说明如何在基于Spring构架的Web应用中使用Acegi,而不是详细介绍其中的每个接口、每个类。注意,即使对已经存在的Spring应用,通过下面介绍的步骤,也可以马上享受到Acegi提供的认证和授权。

    [基础工作]
    在你的Web应用的lib中添加Acegi下载包中的acegi-security.jar

    [web.xml]
    实现认证和授权的最常用的方法是通过filter,Acegi亦是如此,通常Acegi需要在web.xml添加以下5个filter:

    <filter>
      <filter-name>Acegi Channel Processing Filter</filter-name>
      <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
      <init-param>
        <param-name>targetClass</param-name>
        <param-value>net.sf.acegisecurity.securechannel.ChannelProcessingFilter</param-value>
      </init-param>
    </filter>
    <filter>
      <filter-name>Acegi Authentication Processing Filter</filter-name>
      <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
      <init-param>
        <param-name>targetClass</param-name>
        <param-value>net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter</param-value>
      </init-param>
    </filter>
    <filter>
      <filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
      <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
      <init-param>
        <param-name>targetClass</param-name>
        <param-value>net.sf.acegisecurity.ui.basicauth.BasicProcessingFilter</param-value>
      </init-param>
    </filter>
    <filter>
      <filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
      <filter-class>net.sf.acegisecurity.ui.AutoIntegrationFilter</filter-class>
    </filter>
    <filter>
      <filter-name>Acegi HTTP Request Security Filter</filter-name>
      <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
      <init-param>
        <param-name>targetClass</param-name>
        <param-value>net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter</param-value>
      </init-param>
    </filter>


    最先引起迷惑的是net.sf.acegisecurity.util.FilterToBeanProxy,Acegi自己的文档上解释是: “What  FilterToBeanProxy does is delegate the Filter's methods through to a bean which is obtained from the
    Spring application context. This enables the bean to benefit from the Spring application context lifecycle support and configuration flexibility.”,如希望深究的话,去看看源代码应该不难理解。

    再下来就是添加filter-mapping了:
    <filter-mapping>
      <filter-name>Acegi Channel Processing Filter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
      <filter-name>Acegi Authentication Processing Filter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
      <filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
      <filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
      <filter-name>Acegi HTTP Request Security Filter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>


    这里,需要注意以下两点:
    1) 这几个filter的顺序是不能更改的,顺序不对将无法正常工作;
    2) 如果你的应用不需要安全传输,如https,则将"Acegi Channel Processing Filter"相关内容注释掉即可;
    3) 如果你的应用不需要Spring提供的远程访问机制,如Hessian and Burlap,将"Acegi HTTP BASIC Authorization
    Filter"相关内容注释掉即可。

    [applicationContext.xml]
    接下来就是要添加applicationContext.xml中的内容了,从刚才FilterToBeanFactory的解释可以看出,真正的filter都
    在Spring的applicationContext中管理:

    1) 首先,你的数据库中必须具有保存用户名和密码的table,Acegi要求table的schema必须如下:

    CREATE TABLE users (
        username VARCHAR(50) NOT NULL PRIMARY KEY,
        password VARCHAR(50) NOT NULL,
        enabled BIT NOT NULL
    );
    CREATE TABLE authorities (
        username VARCHAR(50) NOT NULL,
        authority VARCHAR(50) NOT NULL
    );
    CREATE UNIQUE INDEX ix_auth_username ON authorities ( username, authority );
    ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users foreign key (username) REFERENCES users
    (username);


    2) 添加访问你的数据库的datasource和Acegi的jdbcDao,如下:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
      <property name="url"><value>${jdbc.url}</value></property>
      <property name="username"><value>${jdbc.username}</value></property>
      <property name="password"><value>${jdbc.password}</value></property>
    </bean>
    <bean id="jdbcDaoImpl" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
      <property name="dataSource"><ref bean="dataSource"/></property>
    </bean>


    3) 添加DaoAuthenticationProvider:

    <bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
      <property name="authenticationDao"><ref bean="authenticationDao"/></property>
      <property name="userCache"><ref bean="userCache"/></property>
    </bean>

    <bean id="userCache" class="net.sf.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
      <property name="minutesToIdle"><value>5</value></property>
    </bean>


    如果你需要对密码加密,则在daoAuthenticationProvider中加入:<property name="passwordEncoder"><ref
    bean="passwordEncoder"/></property>,Acegi提供了几种加密方法,详细情况可看包
    net.sf.acegisecurity.providers.encoding

    4) 添加authenticationManager:

    <bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
      <property name="providers">
        <list>
          <ref bean="daoAuthenticationProvider"/>
        </list>
       </property>
    </bean>


    5) 添加accessDecisionManager:

    <bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
      <property name="allowIfAllAbstainDecisions">
        <value>false</value>
      </property>
      <property name="decisionVoters">
        <list><ref bean="roleVoter"/></list>
      </property>
    </bean>
    <bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>


    6) 添加authenticationProcessingFilterEntryPoint:

    <bean id="authenticationProcessingFilterEntryPoint" 
    class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
      <property name="loginFormUrl"><value>/acegilogin.jsp</value></property>
      <property name="forceHttps"><value>false</value></property>
    </bean>


    其中acegilogin.jsp是登陆页面,一个最简单的登录页面如下:

    <%@ taglib prefix='c' uri='http://java.sun.com/jstl/core' %>
    <%@ page import="net.sf.acegisecurity.ui.AbstractProcessingFilter" %>
    <%@ page import="net.sf.acegisecurity.AuthenticationException" %>
    <html>
      <head>
        <title>Login</title>
      </head>

      <body>
        <h1>Login</h1>
        <form action="<c:url value='j_acegi_security_check'/>" method="POST">
          <table>
            <tr><td>User:</td><td><input type='text' name='j_username'></td></tr>
            <tr><td>Password:</td><td><input type='password' name='j_password'></td></tr>
            <tr><td colspan='2'><input name="submit" type="submit"></td></tr>
            <tr><td colspan='2'><input name="reset" type="reset"></td></tr>
          </table>
        </form>
      </body>
    </html>


    7) 添加filterInvocationInterceptor:

    <bean id="filterInvocationInterceptor" 
    class="net.sf.acegisecurity.intercept.web.FilterSecurityInterceptor">
      <property name="authenticationManager">
        <ref bean="authenticationManager"/>
      </property>
      <property name="accessDecisionManager">
        <ref bean="accessDecisionManager"/>
      </property>
      <property name="objectDefinitionSource">
        <value>
          CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
          \A/sec/administrator.*\Z=ROLE_SUPERVISOR
          \A/sec/user.*\Z=ROLE_TELLER
        </value>
      </property>
    </bean>


    这里请注意,要objectDefinitionSource中定义哪些页面需要权限访问,需要根据自己的应用需求进行修改,我上面给出
    的定义的意思是这样的:
    a. CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON意思是在比较请求路径时全部转换为小写
    b. \A/sec/administrator.*\Z=ROLE_SUPERVISOR意思是只有权限为ROLE_SUPERVISOR才能访问/sec/administrator*的页面
    c. \A/sec/user.*\Z=ROLE_TELLER意思是只有权限为ROLE_TELLER的用户才能访问/sec/user*的页面

    8) 添加securityEnforcementFilter:

    <bean id="securityEnforcementFilter" class="net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter">
      <property name="filterSecurityInterceptor">
        <ref bean="filterInvocationInterceptor"/>
      </property>
      <property name="authenticationEntryPoint">
        <ref bean="authenticationProcessingFilterEntryPoint"/>
      </property>
    </bean>


    9) 添加authenticationProcessingFilter:

    <bean id="authenticationProcessingFilter" 
    class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
      <property name="authenticationManager">
        <ref bean="authenticationManager"/>
      </property>
      <property name="authenticationFailureUrl">
        <value>/loginerror.jsp</value>
      </property>
      <property name="defaultTargetUrl">
        <value>/</value>
      </property>
      <property name="filterProcessesUrl">
        <value>/j_acegi_security_check</value>
      </property>
    </bean>

    其中authenticationFailureUrl是认证失败的页面。

    10) 如果需要一些页面通过安全通道的话,添加下面的配置:

    <bean id="channelProcessingFilter" class="net.sf.acegisecurity.securechannel.ChannelProcessingFilter">
      <property name="channelDecisionManager">
        <ref bean="channelDecisionManager"/>
      </property>
      <property name="filterInvocationDefinitionSource">
        <value>
          CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
          \A/sec/administrator.*\Z=REQUIRES_SECURE_CHANNEL
          \A/acegilogin.jsp.*\Z=REQUIRES_SECURE_CHANNEL
          \A/j_acegi_security_check.*\Z=REQUIRES_SECURE_CHANNEL
          \A.*\Z=REQUIRES_INSECURE_CHANNEL
        </value>
      </property>
    </bean>

    <bean id="channelDecisionManager" class="net.sf.acegisecurity.securechannel.ChannelDecisionManagerImpl">
      <property name="channelProcessors">
        <list>
          <ref bean="secureChannelProcessor"/>
          <ref bean="insecureChannelProcessor"/>
        </list>
      </property>
    </bean>
    <bean id="secureChannelProcessor" class="net.sf.acegisecurity.securechannel.SecureChannelProcessor"/>
    <bean id="insecureChannelProcessor" class="net.sf.acegisecurity.securechannel.InsecureChannelProcessor"/>


    [缺少了什么?]
    Acegi目前提供了两种"secure object",分别对页面和方法进行安全认证管理,我这里介绍的只是利用
    FilterSecurityInterceptor对访问页面的权限控制,除此之外,Acegi还提供了另外一个Interceptor――
    MethodSecurityInterceptor,它结合runAsManager可实现对对象中的方法的权限控制,使用方法可参看Acegi自带的文档
    和contact范例。

    [最后要说的]
    本来以为只是说明如何使用Acegi而已,应该非常简单,但真正写起来才发现想要条理清楚的理顺所有需要的bean还是很
    困难的,但愿我没有遗漏太多东西,如果我的文章有什么遗漏或错误的话,还请参看Acegi自带的quick-start范例,但请
    注意,这个范例是不能直接拿来用的。
    分析和学习Spring中的jpetstore用户管理
      存在用户的系统,必然需要用户的登录和认证,今天就通过分析Spring中自带的jpetstore的例子来学习一下如何实现在Spring构架的系统中用户登录。
    1、首先从注册用户开始,先看看jpetstore-servlet.xml中关于注册用户的bean定义,从定义命名中就可以看出下面这段就是注册用户的:
      
    <bean name="/shop/newAccount.do" class="org.springframework.samples.jpetstore.web.spring.AccountFormController">
        <property name="petStore"><ref bean="petStore"/></property>
        <property name="validator"><ref bean="accountValidator"/></property>
        <property name="successView"><value>index</value></property>
      </bean>

    1). formView呢?从AccountFormController的构造函数中得到,原来为EditAccountForm;  
    2). EditoAccountForm.jsp中显得非常乱,其实没有多少难理解的地方,最主要的是这个form既是添加新用户的,又是编辑用户信息的,所以显得有点乱糟糟的。
    2、添加好了新用户,接下来看看如何登录,在jpetstore-servlet中发现这两个相关bean定义,如下:
      
    <bean name="/shop/signon.do" class="org.springframework.samples.jpetstore.web.spring.SignonController">
        <property name="petStore"><ref bean="petStore"/></property>
      </bean>
      <bean name="/shop/signonForm.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName"><value>SignonForm</value></property>
      </bean>

    1). 第二个bean是在运行时用户输入用户名和密码的form,叫做SignonForm,对于这个 ParameterizableViewController,用文档里的话说这是最简单的Controller,其作用就是在运行中指向 Controller而不是直接指向jsp文件,仅此而已。
    2). SignonForm.jsp,里面就是一个简单的form,其action就是第一个bean,即/shop/signon.do,最需要注意的是 signonForwardAction,其主要作用是forward到需要输入用户名和密码的那个页面上去,这个变量哪里来的呢?看看下面:
      
    <bean id="secureHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors">
          <list>
            <ref bean="signonInterceptor"/>
          </list>
        </property>
        <property name="urlMap">
          <map>
            <entry key="/shop/editAccount.do"><ref local="secure_editAccount"/></entry>
            <entry key="/shop/listOrders.do"><ref local="secure_listOrders"/></entry>
            <entry key="/shop/newOrder.do"><ref local="secure_newOrder"/></entry>
            <entry key="/shop/viewOrder.do"><ref local="secure_viewOrder"/></entry>
          </map>
        </property>
      </bean>

      原来,上面的signonInterceptor实现了preHandle,因此在请求上面的map页面时,首先要经过这个Interceptor,看看 SignonInterceptor的源码,原来在其中为signon.jsp赋予一个signonForwardAction对象,呵呵,总算明白了。
    3). 接下来去学习一下SignonController,其主体部分中可以看出,首先取出用户输入的username和password,然后到数据库中验证 有没有这个用户,如果没有这个用户,返回各错误页面;如果成功,首先生成一个UserSession对象,在request的session加入这个 userSession,注意这部分代码中给出了PagedListHolder分页的简单使用方法,关于分页显示,以后再学习吧。
    3、登录成功后,就可以根据不同的用户设施不同的行为了,取得用户信息,无非就是从session取出userSession即可。
    posted @ 2006-12-27 23:20 海思 阅读(208) | 评论 (0)编辑 收藏

    或许你正需要面试软件测试工程师,或许你准备去应聘软件测试工程师,以下是一些可能注意的问题。(选译)

    有什么原因让你参与到测试和质量管理中来?
    什么是测试生命周期,解释一下它的各个阶段?
    测试和质量保证有什么不同?
    什么是Negative测试?
    在之前做测试的过程总遇到过哪些问题?你是如何解决的?
    你是如何给你的测试和质量保证团队力量的?
    你是如何定义质量管理的?
    你最喜欢测试和质量管理什么地方?
    你最不喜欢什么地方?
    什么是瀑布式开发方法,你是否认同所有的步骤?
    什么是V-模式开发方法,你是否认同这个模型?
    什么是CMM?你工作过的公司的级别是怎么样的?
    什么才算好的测试人员?

    更多问题,可以查看以下内容:

    Could you tell me two things you did in your previous assignment (QA/Testing related hopefully) that you are proud of?
    List 5 words that best describe your strengths.
    What are two of your weaknesses?
    What methodologies have you used to develop test cases?
    In an application currently in production, one module of code is being modified. Is it necessary to re- test the whole application or is it enough to just test functionality associated with that module?
    Define each of the following and explain how each relates to the other: Unit, System, and Integration testing.
    Define Verification and Validation. Explain the differences between the two.
    Explain the differences between White-box, Gray-box, and Black-box testing.
    How do you go about going into a new organization? How do you assimilate?
    Define the following and explain their usefulness: Change Management, Configuration Management, Version Control, and Defect Tracking.
    What is ISO 9000? Have you ever been in an ISO shop?
    When are you done testing?
    What is the difference between a test strategy and a test plan?
    What is ISO 9003? Why is it important
    What are ISO standards? Why are they important?
    What is IEEE 829? (This standard is important for Software Test Documentation-Why?)
    What is IEEE? Why is it important?
    Do you support automated testing? Why?
    We have a testing assignment that is time-driven. Do you think automated tests are the best solution?
    What is your experience with change control? Our development team has only 10 members. Do you think managing change is such a big deal for us?
    Are reusable test cases a big plus of automated testing and explain why.
    Can you build a good audit trail using Compuware's QACenter products. Explain why.
    How important is Change Management in today's computing environments?
    Do you think tools are required for managing change. Explain and please list some tools/practices which can help you managing change.
    We believe in ad-hoc software processes for projects. Do you agree with this? Please explain your answer.
    When is a good time for system testing?
    Are regression tests required or do you feel there is a better use for resources?
    Our software designers use UML for modeling applications. Based on their use cases, we would like to plan a test strategy. Do you agree with this approach or would this mean more effort for the testers.
    Tell me about a difficult time you had at work and how you worked through it.
    Give me an example of something you tried at work but did not work out so you had to go at things another way.
    How can one file compare future dated output files from a program which has change, against the baseline run which used current date for input. The client does not want to mask dates on the output files to allow compares. - Answer-Rerun baseline and future date input files same # of days as future dated run of program with change. Now run a file compare against the baseline future dated output and the changed programs' future dated output.

    Interviewing Suggestions
    If you do not recognize a term ask for further definition. You may know the methodology/term but you have used a different name for it.
    Always keep in mind that the employer wants to know what you are going to do for them, with that you should always stay/be positive.

    Preinterview Questions
    What is the structure of the company?
    Who is going to do the interview-possible background information of interviewer?
    What is the employer's environment (platforms, tools, etc.)?
    What are the employer's methods and processes used in software arena?
    What is the employer's philosophy?
    What is the project all about you are interviewing for-as much information as possible.
    Any terminologies that the company may use.

    (该文转载自Matrix,原文地址:http://www.matrix.org.cn/resource/article/44/44430_software+test.html



    Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=791907

    posted @ 2006-12-24 22:49 海思 阅读(443) | 评论 (0)编辑 收藏

         摘要: 李涛,Sun中国工程研究院工程师 概述 1:三个新加的多线程包 ...  阅读全文
    posted @ 2006-12-24 22:37 海思 阅读(338) | 评论 (1)编辑 收藏

    利用XMLBean轻轻松松读写XML

    作者:叶枫




    版权声明:本文可以自由转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明
    作者:叶枫(http://blog.matrix.org.cn/page/叶枫)
    原文:[http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html]http://www.matrix.org.cn/resource/article/44/44027_XMLBean.html[/url]
    关键字:XML XMLBean Parser

    一、关于XML解析

      XML在Java应用程序里变得越来越重要, 广泛应用于数据存储和
    交换. 比如我们常见的配置文件,都是以XML方式存储的. XML还应用
    于Java Message Service和Web Services等技术作为数据交换.
    因此,正确读写XML文档是XML应用的基础.
      Java提供了SAX和DOM两种方式用于解析XML,但即便如此,要读写一个
    稍微复杂的XML,也不是一件容易的事.

    二、XMLBean简介

        Hibernate已经成为目前流行的面向Java环境的对象/关系数据库映射工具.
    在Hibernate等对象/关系数据库映射工具出现之前,对数据库的操作是
    通过JDBC来实现的,对数据库的任何操作,开发人员都要自己写SQL语句
    来实现. 对象/关系数据库映射工具出现后,对数据库的操作转成对
    JavaBean的操作,极大方便了数据库开发. 所以如果有一个类似的工具能够
    实现将对XML的读写转成对JavaBean的操作,将会简化XML的读写,即使对XML
    不熟悉的开发人员也能方便地读写XML. 这个工具就是XMLBean.

    三、准备XMLBean和XML文档

       XMLBean是Apache的一个开源项目,可以从http://www.apache.org下载,
    最新的版本是2.0. 解压后目录如下:
    xmlbean2.0.0
         +---bin
         +---docs
         +---lib
         +---samples
         +---schemas


    另外还要准备一个XML文档(customers.xml),
    在本文的例子里,我们将对这个文档进行读写操作. 文档源码如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <Customers>
        <customer>
                <id>1</id>
                <gender>female</gender>
                <firstname>Jessica</firstname>
                <lastname>Lim</lastname>
                <phoneNumber>1234567</phoneNumber>
                <address>
                    <primaryAddress>
                            <postalCode>350106</postalCode>
                            <addressLine1>#25-1</addressLine1>
                            <addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
                    </primaryAddress>
                    <billingAddress>
                            <receiver>Ms Danielle</receiver>
                            <postalCode>350107</postalCode>
                            <addressLine1>#167</addressLine1>
                            <addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
                    </billingAddress>
                </address>
        </customer>
        <customer>
                <id>2</id>
                <gender>male</gender>
                <firstname>David</firstname>
                <lastname>Bill</lastname>
                <phoneNumber>808182</phoneNumber>
                <address>
                    <primaryAddress>
                            <postalCode>319087</postalCode>
                            <addressLine1>1033 WS St.</addressLine1>
                            <addressLine2>Tima Road</addressLine2>
                    </primaryAddress>
                    <billingAddress>
                            <receiver>Mr William</receiver>
                            <postalCode>672993</postalCode>
                            <addressLine1>1033 WS St.</addressLine1>
                            <addressLine2>Tima Road</addressLine2>
                    </billingAddress>
                </address>
        </customer>
    </Customers>


    这是一个客户的数据模型,每个客户都有客户编号(ID),姓名,性别(gender),
    电话号码(phoneNumber)和地址,其中地址有两个: 首要地址(PrimaryAddress)
    和帐单地址(BillingAddress),每个地址有邮编,地址1,和地址2组成.
    其中帐单地址还有收件人(receiver).

        此外,还要准备一个配置文件(文件名customer.xsdconfig),这个文件的
    作用我后面会讲,它的内容如下:

    <xb:config xmlns:xb="http://xml.apache.org/xmlbeans/2004/02/xbean/config">

      <xb:namespace>
        <xb:package>sample.xmlbean</xb:package>
      </xb:namespace>

    </xb:config>


    四、XMLBean使用步骤

        和其他面向Java环境的对象/关系数据库映射工具的使用步骤一样,
    在正式使用XMLBean前,我们要作两个准备.

        1. 生成XML Schema文件

           什么是XML Schema文件? 正常情况下,每个XML文件都有一个Schema文件,
           XML Schema文件是一个XML的约束文件,它定义了XML文件的结构和元素.
           以及对元素和结构的约束. 通俗地讲,如果说XML文件是数据库里的记录,
           那么Schema就是表结构定义.

           为什么需要这个文件? XMLBean需要通过这个文件知道一个XML文件的
           结构以及约束,比如数据类型等. 利用这个Schema文件,XMLBean将会产生
           一系列相关的Java Classes来实现对XML的操作. 而作为开发人员,则是
           利用XMLBean产生的Java Classes来完成对XML的操作而不需要SAX或DOM.

           怎样产生这个Schema文件呢? 如果对于熟悉XML的开发人员,可以自己来
           写这个Schema文件,对于不熟悉XML的开发人员,可以通过一些工具来完成.
           比较有名的如XMLSPY和Stylus Studio都可以通过XML文件来生成Schema
           文件. 加入我们已经生成这个Schema文件(customer.xsd):
          

           <?xml version="1.0" encoding="UTF-8"?>
           <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
                      elementFormDefault="qualified">
             <xs:element name="Customers">
               <xs:complexType>
                 <xs:sequence>
                   <xs:element maxOccurs="unbounded" name="customer"
                               type="customerType"/>
                 </xs:sequence>
               </xs:complexType>
             </xs:element>
           <xs:complexType name="customerType">
                 <xs:sequence>
                   <xs:element name="id" type="xs:int"/>
                   <xs:element name="gender" type="xs:string"/>
                   <xs:element name="firstname" type="xs:string"/>
                   <xs:element name="lastname" type="xs:string"/>
                   <xs:element name="phoneNumber" type="xs:string"/>
                   <xs:element name="address" type="addressType"/>
                 </xs:sequence>
           </xs:complexType>
             <xs:complexType name="addressType">
                 <xs:sequence>
                   <xs:element name="primaryAddress" type="primaryAddressType"/>
                   <xs:element name="billingAddress" type="billingAddressType"/>
                 </xs:sequence>
             </xs:complexType>

             <xs:complexType name="primaryAddressType">
                 <xs:sequence>
                   <xs:element name="postalCode" type="xs:string"/>
                   <xs:element name="addressLine1" type="xs:string"/>
                   <xs:element name="addressLine2" type="xs:string"/>
                 </xs:sequence>
             </xs:complexType>
             <xs:complexType name="billingAddressType">
                 <xs:sequence>
                       <xs:element name="receiver" type="xs:string"/>
                   <xs:element name="postalCode" type="xs:string"/>
                   <xs:element name="addressLine1" type="xs:string"/>
                   <xs:element name="addressLine2" type="xs:string"/>
                 </xs:sequence>
             </xs:complexType>
           </xs:schema>
          


        2. 利用scomp来生成Java Classes

           scomp是XMLBean提供的一个编译工具,它在bin的目录下. 通过这个工具,
           我们可以将以上的Schema文件生成Java Classes.
           scomp的语法如下:-

          

           scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
          


           主要参数说明:
           -src [dir]                  -- 生成的Java Classes存放目录
         -srconly                  -- 不编译Java Classes,不产生Jar文件
         -out [jarFileName]  -- 生成的Jar文件,缺省是xmltypes.jar
           -compiler                 -- Java编译器的路径,即Javac的位置
           schemaFile.xsd    -- XML Schema文件位置
           config.xsdconfig   -- xsdconfig文件的位置, 这个文件主要用来制定生成的Java Class
                                  的一些文件名规则和Package的名称,在本文,package是sample.xmlbean

           在本文,我是这样运行的:
          

           scomp -src build\src  -out build\customerXmlBean.jar schema\customer.xsd
                 -compiler C:\jdk142_04\bin\javac customer.xsdconfig
          


           这个命令行的意思是告诉scomp生成customerXmlBean.jar,放在build目录下,同时
           生成源代码放在build\src下, Schema文件是customer.xsd,xsdconfig文件是customer.xsdconfig.

           其实, 生成的Java源代码没有多大作用,我们要的是jar文件.我们先看一下build\src\sample\xmlbean下生成的Classes.
          

              CustomersDocument.java    -- 整个XML文档的Java Class映射
           CustomerType.java              -- 节点sustomer的映射
           AddressType.java                 -- 节点address的映射
           BillingAddressType.java        -- 节点billingAddress的映射
           PrimaryAddressType.java      -- 节点primaryAddress的映射
        


           好了,到此我们所有的准备工作已经完成了. 下面就开始进入重点:利用刚才生成的jar文件读写XML.

    五、利用XMLBean读XML文件

        新建一个Java Project,将XMLBean2.0.0\lib\下的Jar文件和刚才我们生成的customerXmlBean.jar加入
        到Project的ClassPath.

        新建一个Java Class: CustomerXMLBean.  源码如下:
        

        package com.sample.reader;

        import java.io.File;
        
        import sample.xmlbean.*;
        import org.apache.commons.beanutils.BeanUtils;
        import org.apache.xmlbeans.XmlOptions;
        public class CustomerXMLBean {
        private String filename = null;
        
        public CustomerXMLBean(String filename) {
                super();
                this.filename = filename;
        }

        public void customerReader() {
                try {
                  File xmlFile = new File(filename);
                  CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
                  CustomerType[] customers = doc.getCustomers().getCustomerArray();
              
                  for (int i = 0; i < customers.length; i++) {
                    CustomerType customer = customers[i];
                    println("Customer#" + i);
                    println("Customer ID:" + customer.getId());
                    println("First name:" + customer.getFirstname());
                    println("Last name:" + customer.getLastname());
                    println("Gender:" + customer.getGender());
                    println("PhoneNumber:" + customer.getPhoneNumber());
                    // Primary address
                    PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
                    println("PrimaryAddress:");
                    println("PostalCode:" + primaryAddress.getPostalCode());
                    println("AddressLine1:" + primaryAddress.getAddressLine1());
                    println("AddressLine2:" + primaryAddress.getAddressLine2());
                    // Billing address
                    BillingAddressType billingAddress = customer.getAddress().getBillingAddress();
                    println("BillingAddress:");
                    println("Receiver:" + billingAddress.getReceiver());
                    println("PostalCode:" + billingAddress.getPostalCode());
                    println("AddressLine1:" + billingAddress.getAddressLine1());
                    println("AddressLine2:" + billingAddress.getAddressLine2());
                
                  }
                } catch (Exception ex) {
                        ex.printStackTrace();
                }
        }
        private void println(String str) {
              System.out.println(str);
        }
       public static void main(String[] args) {
          String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml";
                      
         CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
                       customerXMLBean.customerReader();
        }

        }
        


        运行它,参看输出结果:
        

           Customer#0
           Customer ID:1
           First name:Jessica
           Last name:Lim
           Gender:female
           PhoneNumber:1234567
           PrimaryAddress:
           PostalCode:350106
           AddressLine1:#25-1
           AddressLine2:SHINSAYAMA 2-CHOME
           BillingAddress:
           Receiver:Ms Danielle
           PostalCode:350107
           AddressLine1:#167
           AddressLine2:NORTH TOWER HARBOUR CITY

           Customer#1
           Customer ID:2
           First name:David
           Last name:Bill
           Gender:male
           PhoneNumber:808182
           PrimaryAddress:
           PostalCode:319087
           AddressLine1:1033 WS St.
           AddressLine2:Tima Road
           BillingAddress:
           Receiver:Mr William
           PostalCode:672993
           AddressLine1:1033 WS St.
           AddressLine2:Tima Road
        

        怎么样,是不是很轻松? XMLBean的威力.

    六、利用XMLBean写XML文件

        利用XMLBean创建一个XML文档也是一件轻而易举的事.我们再增加一个Method,
        请看一下的Java Class:
        

        public void createCustomer() {
        try {
            // Create Document
            CustomersDocument doc = CustomersDocument.Factory.newInstance();
            // Add new customer
            CustomerType customer = doc.addNewCustomers().addNewCustomer();
            // set customer info
            customer.setId(3);
            customer.setFirstname("Jessica");
            customer.setLastname("Lim");
            customer.setGender("female");
            customer.setPhoneNumber("1234567");
            // Add new address
            AddressType address = customer.addNewAddress();
            // Add new PrimaryAddress
            PrimaryAddressType primaryAddress = address.addNewPrimaryAddress();
            primaryAddress.setPostalCode("350106");
            primaryAddress.setAddressLine1("#25-1");
            primaryAddress.setAddressLine2("SHINSAYAMA 2-CHOME");

            // Add new BillingAddress
            BillingAddressType billingAddress = address.addNewBillingAddress();
            billingAddress.setReceiver("Ms Danielle");
            billingAddress.setPostalCode("350107");
            billingAddress.setAddressLine1("#167");
            billingAddress.setAddressLine2("NORTH TOWER HARBOUR CITY");

            File xmlFile = new File(filename);
            doc.save(xmlFile);
            } catch (Exception ex) {
                    ex.printStackTrace();
            }

      }
        

        修改main method.
        

        public static void main(String[] args) {
        String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
            CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
            customerXMLBean.createCustomer();
        }
        

        运行,打开customers_new.xml:
        

        <?xml version="1.0" encoding="UTF-8"?>
        <Customers>
        <customer>
                <id>3</id>
                <gender>female</gender>
                <firstname>Jessica</firstname>
                <lastname>Lim</lastname>
                <phoneNumber>1234567</phoneNumber>
                <address>
                        <primaryAddress>
                             <postalCode>350106</postalCode>
                             <addressLine1>#25-1</addressLine1>
                                           <addressLine2>SHINSAYAMA 2-CHOME</addressLine2>
                        </primaryAddress>
                        <billingAddress>
                            <receiver>Ms Danielle</receiver>
                            <postalCode>350107</postalCode>
                           <addressLine1>#167</addressLine1>
                           <addressLine2>NORTH TOWER HARBOUR CITY</addressLine2>
                        </billingAddress>
                        </address>
                </customer>
        </Customers>
        



    七、利用XMLBean修改XML文件

        我们再增加一个Method:
        

          public void updateCustomer(int id,String lastname) {
             try {
            File xmlFile = new File(filename);
            CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
            CustomerType[] customers = doc.getCustomers().getCustomerArray();
          
            for (int i = 0; i < customers.length; i++) {
               CustomerType customer = customers[i];
              if(customer.getId()==id){
                    customer.setLastname(lastname);
                    break;
                }
            }
            doc.save(xmlFile);
             } catch (Exception ex) {
              ex.printStackTrace();
             }
               }
        

        main method:
        

        public static void main(String[] args) {
         String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
                        
        CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
                        
        customerXMLBean.updateCustomer(3,"last");
        }
        

        运行之后,我们将会看到客户编号为3的客户的lastname已经改为last.

    八、利用XMLBean删除一个customer

        再增加一个Method:
        

        public void deleteCustomer(int id) {
         try {
          File xmlFile = new File(filename);
         CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
        CustomerType[] customers = doc.getCustomers().getCustomerArray();

       for (int i = 0; i < customers.length; i++) {
            CustomerType customer = customers[i];
            if(customer.getId()==id){
                            customer.setNil() ;
                            break;
                   }
       }
       doc.save(xmlFile);
       } catch (Exception ex) {
            ex.printStackTrace();
            }
       }


             main method:
        

        public static void main(String[] args) {
        String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
                        
        CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
                        
        customerXMLBean.deleteCustomer(3);
        }

            
    运行,我们将会看到客户编号为3的客户的资料已经被删除.

    九、查询XML

        除了本文在以上讲述的,利用XMLBean能轻轻松松完成XML的读写操作外,结合XPath和XQuery,
       XMLBean还能完成象SQL查询数据库一样方便地查询XML数据. 关于XML查询以及如何创建XML数据库, 我将在另一篇文章里讨论.



    十、结束语
        XMLBean能帮助我们轻易读写XML,这将有助于我们降低XML的学习和使用,有了这个基础,
        开发人员将为学习更多地XML相关技术和Web Services,JMS等其他J2EE技术打下良好地基础.


    关于作者:
    叶枫:热爱Java和Oracle. 在软件开发有近10年, 目前在国外一家美国大公司担任SA, 负责技术研究。作者Blog:http://blog.matrix.org.cn/page/叶枫
    posted @ 2006-12-21 23:10 海思 阅读(250) | 评论 (0)编辑 收藏

         摘要: 作者的blog: http://yuwang881.blog.sohu.com/http://blog.csdn.net/javachannel/archive/2006/05/24/752437.aspx王昱 yuwang881@gmail.com   博客地址http://yuwang881.blog.sohu.com摘要:单点登录(SSO)的技术被越来越广泛地运用到各个领域的软件系统当中。本...  阅读全文
    posted @ 2006-12-21 22:42 海思 阅读(378) | 评论 (0)编辑 收藏

    公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成.排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。1、地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码,按GB/T2260的规定执行。

      2、出生日期码表示编码对象出生的年、月、日,按GB/T7408的规定执行。年、月、日代码之间不用分隔符。例:某人出生日期为1966年10月26日,其出生日期码为19661026。

      3、顺序码表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数千分配给女性。

      4、校验码校验码采用ISO7064:1983,MOD11-2校验码系统。

      1)十七位数字本体码加权求和公式 S=Sum(Ai*Wi),i=0,...,16,先对前17位数字的权求和 Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi:7910584216379105842

      2)计算模 Y=mod(S,11)

      3)通过模得到对应的校验码 :012345678910 验码:10X98765432

      下面是java实现的代码

      /**IDCard.javaCreatedon2004-11-517:03:37**/packageorg.yz21.study.idcard;

      /***@authorviolin2004-11-517:03:37*Copyrightwww.yz21.org2003-2004*/publicclassIDCard{//wi=2(n-1)(mod11)finalint[]wi={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1};

      //verifydigitfinalint[]vi={1,0,X,9,8,7,6,5,4,3,2};

      privateint[]ai=newint[18];

      publicIDCard(){}

      //verifypublicbooleanVerify(Stringidcard){if(idcard.length()==15){idcard=uptoeighteen(idcard);}if(idcard.length()!=18){returnfalse;}Stringverify=idcard.substring(17,18);if(verify.equals(getVerify(idcard))){returntrue;}returnfalse;}

      //getverifypublicStringgetVerify(Stringeightcardid){intremaining=0;

      if(eightcardid.length()==18){eightcardid=eightcardid.substring(0,17);}

      if(eightcardid.length()==17){intsum=0;for(inti=0;i<17;i++){Stringk=eightcardid.substring(i,i+1);ai=Integer.parseInt(k);}

      for(inti=0;i<17;i++){sum=sum+wi*ai;}remaining=sum%11;}

      returnremaining==2?"X":String.valueOf(vi[remaining]);}

      //15updateto18publicStringuptoeighteen(Stringfifteencardid){Stringeightcardid=fifteencardid.substring(0,6);eightcardid=eightcardid+"19";eightcardid=eightcardid+fifteencardid.substring(6,15);eightcardid=eightcardid+getVerify(eightcardid);returneightcardid;}

      }

      测试代码:使用的单元测试工具是junit

      /**IDCardTest.javaCreatedon2004-11-517:32:12**/packageorg.yz21.study.idcard;

      importjunit.framework.Test;importjunit.framework.TestCase;importjunit.framework.TestSuite;

      /***@authorviolin2004-11-517:32:12*Copyrightwww.yz21.org2003-2004*/publicclassIDCardTestextendsTestCase{

      privateStringidcard1="11010519491231002X";privateStringidcard2="440524188001010014";

      publicvoidtestVerify(){IDCardidcard=newIDCard();this.assertTrue(idcard.Verify(idcard1));this.assertTrue(idcard.Verify(idcard2));}

      publicstaticTestsuite(){returnnewTestSuite(IDCardTest.class);}

      publicstaticvoidmain(String[]args){junit.textui.TestRunner.run(suite());}}
    posted @ 2006-12-21 21:47 海思 阅读(352) | 评论 (0)编辑 收藏

    说明:复制表(只复制结构,源表名:a  新表名:b)
    SQL:  select  *  into  b  from  a  where  1<>1
    说明:拷贝表(拷贝数据,源表名:a  目标表名:b)
    SQL:  insert  into  b(a,  b,  c)  select  d,e,f  from  b;
    说明:显示文章、提交人和最后回复时间
    SQL:  select  a.title,a.username,b.adddate  from  table  a,(select  max(adddate)  adddate  from  table  where  table.title=a.title)  b
    说明:外连接查询(表名1:a  表名2:b)
    SQL:  select  a.a,  a.b,  a.c,  b.c,  b.d,  b.f  from  a  LEFT  OUT  JOIN  b  ON  a.a  =  b.c
    说明:日程安排提前五分钟提醒
    SQL:    select  *  from  日程安排  where  datediff('minute',f开始时间,getdate())>5
    说明:两张关联表,删除主表中已经在副表中没有的信息
    SQL:    
    delete  from  info  where  not  exists  (  select  *  from  infobz  where  info.infid=infobz.infid  )  
    说明:--
    SQL:    
    SELECT  A.NUM,  A.NAME,  B.UPD_DATE,  B.PREV_UPD_DATE
       FROM  TABLE1,  
           (SELECT  X.NUM,  X.UPD_DATE,  Y.UPD_DATE  PREV_UPD_DATE
                   FROM  (SELECT  NUM,  UPD_DATE,  INBOUND_QTY,  STOCK_ONHAND
                                   FROM  TABLE2
                               WHERE  TO_CHAR(UPD_DATE,'YYYY/MM')  =  TO_CHAR(SYSDATE,  'YYYY/MM'))  X,  
                           (SELECT  NUM,  UPD_DATE,  STOCK_ONHAND
                                   FROM  TABLE2
                               WHERE  TO_CHAR(UPD_DATE,'YYYY/MM')  =  
                                           TO_CHAR(TO_DATE(TO_CHAR(SYSDATE,  'YYYY/MM')  ¦¦  '/01','YYYY/MM/DD')  -  1,  'YYYY/MM')  )  Y,  
                   WHERE  X.NUM  =  Y.NUM  (+)
                       AND  X.INBOUND_QTY  +  NVL(Y.STOCK_ONHAND,0)  <>  X.STOCK_ONHAND  )  B
    WHERE  A.NUM  =  B.NUM
    说明:--
    SQL:    
    select  *  from  studentinfo  where  not  exists(select  *  from  student  where  studentinfo.id=student.id)  and  系名称='"&strdepartmentname&"'  and  专业名称='"&strprofessionname&"'  order  by  性别,生源地,高考总成绩
    说明:
    从数据库中去一年的各单位电话费统计(电话费定额贺电化肥清单两个表来源)
    SQL:  
    SELECT  a.userper,  a.tel,  a.standfee,  TO_CHAR(a.telfeedate,  'yyyy')  AS  telyear,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '01',  a.factration))  AS  JAN,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '02',  a.factration))  AS  FRI,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '03',  a.factration))  AS  MAR,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '04',  a.factration))  AS  APR,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '05',  a.factration))  AS  MAY,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '06',  a.factration))  AS  JUE,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '07',  a.factration))  AS  JUL,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '08',  a.factration))  AS  AGU,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '09',  a.factration))  AS  SEP,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '10',  a.factration))  AS  OCT,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '11',  a.factration))  AS  NOV,
               SUM(decode(TO_CHAR(a.telfeedate,  'mm'),  '12',  a.factration))  AS  DEC
    FROM  (SELECT  a.userper,  a.tel,  a.standfee,  b.telfeedate,  b.factration
                   FROM  TELFEESTAND  a,  TELFEE  b
                   WHERE  a.tel  =  b.telfax)  a
    GROUP  BY  a.userper,  a.tel,  a.standfee,  TO_CHAR(a.telfeedate,  'yyyy')
    说明:四表联查问题:
    SQL:  select  *  from  a  left  inner  join  b  on  a.a=b.b  right  inner  join  c  on  a.a=c.c    inner  join  d  on  a.a=d.d  where  .....

    说明:得到表中最小的未使用的ID号
    SQL:
    SELECT  (CASE  WHEN  EXISTS(SELECT  *  FROM  Handle  b  WHERE  b.HandleID  =  1)  THEN  MIN(HandleID)  +  1  ELSE  1  END)  as  HandleID
    FROM    Handle
    WHERE  NOT  HandleID  IN  (SELECT  a.HandleID  -  1  FROM  Handle  a)
    posted @ 2006-02-22 22:04 海思 阅读(176) | 评论 (0)编辑 收藏

    0.  精彩网址
    http://www.cfanclub.net/fav.htm
    1.vc++技术内幕第四版  (潘爱民)
    ftp://210.32.157.56/课件/c++primer/vc++技术内幕IV(潘爱民).rar
    2.C++经典对话系列
    中文:http://www.jka77.com/book/cvst_cn.chm

    3.MFC  Windows  程序设计(第二版)
    英文版:http://www.jka77.com/book/progmfc2.chm
    中文版:暂无,制作中...
    4.Effective  C++中文版:
    http://dlb.pchome.net/development/reference/effectiveCplus.zip
    5.More  Effective  C++中文版-zhc译
    http://cable.pchome.net/development/reference/MEC0410.zip

    6.More  Effective  C++中文版-候捷译
    http://www.nethovel.com/resources/MoreEffectiveC++(WQ).zip

    7.Essential  C++中文版(全)-候捷译
    http://www.nethovel.com/resources/Essential%20C++中文版(全).rar

    8.深入浅出MFC  2/e
    http://218.30.21.125:8084/ebook/programme/mfc2e.zip

    9.代码大全中文版
    http://www.delphidevelopers.com/  ...  /CodeComplet110.zip

    11.C++经典对话系列
    中文:http://www.jka77.com/book/cvst_cn.chm

    12.MFC  Windows  程序设计(第二版)
    英文版:http://www.jka77.com/book/progmfc2.chm
    中文版:暂无,制作中...

    13.数据结构  C++  语言描述(中文版)
    http://www.code-labs.com/manual/c_c015.zip

    14.Java编程思想中文版
    ftp://202.118.72.12/pub/doc-book/Java/Java编程思想.zip

    15.C++标准库英文版
    ftp://166.111.64.4/incoming/新文件夹/f/The%20C++%20Standard%20Library(with%20TOC).pdf

    16.Windows核心编程  
    英文:http://www.fmdstudio.net/book/prgapps4.zip

    17.TCP-IP详解卷1:协议
    ftp://202.204.4.161/学习资料/TCPIP/TCP-IP详解卷1:协议.pdf

    18.TCP-IP详解卷2:实现
    ftp://202.204.4.161/学习资料/TCPIP/TCP-IP详解卷3:TCP事务协议,HTTP,NNTP.pdf

    19.TCP-IP详解卷3:TCP事务协议
    ftp://202.204.4.161/学习资料/TCPIP/TCP-IP详解卷2:实现.pdf

    20.实用算法的分析与程序设计
    ftp://202.204.8.10/[4]%20编程资源/[%20书籍资料%20]/[算法与数据结构]/实用算法的分析与程序设计.rar

    21.vc++技术内幕第四版  (潘爱民)
    ftp://210.32.157.56/课件/c++primer/vc++技术内幕IV(潘爱民).rar

    22.C++  Primer英文版:
    http://computerstep.w18.net/C/C++%20Primer.zip

    23.Effective  C++中文版:
    http://dlb.pchome.net/development/reference/effectiveCplus.zip

    24.More  Effective  C++中文版-zhc译
    http://cable.pchome.net/development/reference/MEC0410.zip

    25.More  Effective  C++中文版-候捷译
    http://www.nethovel.com/resources/MoreEffectiveC++(WQ).zip

    26.Essential  C++中文版(全)-候捷译
    http://www.nethovel.com/resources/Essential%20C++中文版(全).rar

    27.Programming  Windows程式开发设计指南-Petzoldi著  余孟学  译
    中文版:http://www.nethovel.com/resources/ProgrammingWindows_tw.chm
    英文版:http://www.nethovel.com/resources/Petzoldi.chm

    28.WinAsm32汇编教程-  Iczelion
    http://www.nethovel.com/resources/winasm.chm

    29.Windows  95  程序设计指南-候捷译
    http://www.nethovel.com/resources/win95adg.zip

    30.Thinking  in  C++  2nd  Edition(C++编程思想)
    英文版:http://www.nethovel.com/resources/ThinkinginC++.zip
    中文版:http://www.dingbing.com/book/thinkc.zip

    31.人月神话-中文版
    http://www.goodassister.com/book/rysh.pdf

    32.The  C++  Programming  Language英文
    http://computerstep.w18.net/C/Th  ...  ming%20Language.rar

    33.VC技术内幕第五版  http://www.helpwork.com/downdata  ...  k/vc++2/invcpp5.chm

    34.com技术内幕
    http://www.helpwork.com/book/html/user/download.asp?id=1123

    35.com+技术内幕
    http://www.helpwork.com/book/html/user/download.asp?id=952

    36.新编  Windows  API参考大全
    http://www.4046.com/nnsrc/down/WindowsAPIdq.rar

    37.The  C  programming  Language  //  By  Brian  W.  Kernighan  and  Dennis  M.  Ritchie
    下载地址:http://www.jka77.com/book/The_C_programmin.chm

    38.C语言编程手册
    下载地址:http://www.jka77.com/book/CL.chm

    39.Delphi  7高效数据库程序设计  
    By  李维
    下载地址:http://www.codestudy.net/book/download.asp?id=1163&sort=5

    40.Windows网络编程(第2版)
    By  Anthony  Jones,Jim  Ohlund  清华大学出版社
    下载地址:英文版:http://www.guxiang.com/epubcn/re  ...  rog_for_win_2nd.zip

    41.Windows2000编程技术内幕
    By  Mickey  Williams  机械工业出版社
    下载地址:ftp://ftp.frontfree.net/Pub/Books/C&C++/VC/Windows2000编程技术内幕.rar

    42.数据仓库
    By  W.H.Inmon  清华大学出版社
    下载地址1:http://tips.9hao.com/vvbksd/20011120/数据仓库.zip
    下载地址2:  ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BE%DD%B2%D6%BF%E2/

    43.编码的奥秘
    By  Charles  Petzold  机械工业出版社
    下载地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %B5%C4%B0%C2%C3%D8/

    44.编译原理及实践
    By  Louden,  K.C  机械工业出版社
    下载地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BC%B0%CA%B5%BC%F9/

    45.Inside  C++  Object  Model(深度探索C++对象模型)
    By  Lippman  候捷译
    下载地址:http://www.jka77.com/book/inside-the-cpp-object-model.pdf

    46.C++标准程序库
    By  Josuttis  
    下载地址1:http://www.codestudy.net/book/download.asp?id=1205&sort=5
    下载地址2:  ftp://ftp.math.nankai.edu.cn/Ebook/C_C++/The  Cpp  Standard  Library.pdf

    47.STL源码剖析
    By  候捷
    下载地址:ftp://ftp.math.nankai.edu.cn/Ebook/C_C++/STL源码剖析--侯捷.pdf

    48.C++批判(第三版)  -看看C++的坏话!
    By  I  don't  know
    下载地址:http://www.jka77.com/book/CPPPP.pdf

    49.程序设计实践
    下载地址:ftp://ftp.math.nankai.edu.cn/Ebo  ...  %BC%C6%CA%B5%BC%F9/

    50.c++沉思录
    By  Andrew  Koenig  Barbara  Moo  人民邮电出版社
    下载地址:http://www.codestudy.net/book/download.asp?id=1261&sort=5

    51.C++Builder4技术内幕  (这本书俺不知道好不好:-))
    By  I  don't  Know
    下载地址:http://www.codestudy.net/book/download.asp?id=1254&sort=5

    52.下面两本书一般大家硬盘里都有的吧,而且很老了,但是为了全面,就提上来吧
    (1)Windows  95  程式设计指南  -  候捷
    下载地址:http://jjhou.csdn.net/win95-a-developers-guide.pdf
    (2)Windows  95  系统程式设计大奥秘  -  候捷
    下载地址:http://jjhou.csdn.net/windows95-system-programming-secrets.pdf

    53.  中国大百科全书·数学
    下载地址:ftp://ftp.math.nankai.edu.cn/Ebook/中国大百科全书/中国大百科全书·数学.pdf

    54、4.0M  Bjarne  Stroustrup  -  The  C++  Programming  Language
    http://www.u-n-f.com/books/archi  ...  g%20Language.tar.gz

    55、1.0M  Richard  Stevens  -  TCP-IP  Illustrated
    http://www.u-n-f.com/books/archive/TCP-IP%20Illustrated.tar.gz

    56、4.5M  Randall  Hyde  -  Art  Of  Assembly
    http://www.u-n-f.com/books/archi  ...  f%20Assembly.tar.gz

    57、2.1M  M.  Abrash  -  Zen  of  Graphics  Programming
    http://www.u-n-f.com/books/archi  ...  s%20Programming.zip

    58、249k  Kernighan  and  Ritche  -  The  C  Programming  Language
    http://www.u-n-f.com/books/archi  ...  ming%20Language.zip

    59、3.3M  Bruce  Schneier  -  Applied  Cryptography
    http://www.u-n-f.com/books/archi  ...  %20Cryptography.zip

    60、PHP4_Grundlagen_und_Profiwissen
    http://www.u-n-f.com/books/archi  ...  und_Profiwissen.pdf

    61.《C++  Builder高级编程技术》  
    http://www.dingbing.com/book/builder.zip

    62.《VC++  6.0  TLR  模板库参考手册》
    http://www.easysea.com/diannao/download/prog/c/mbkc.zip

    63.《BORLAND  C++  BUILDER  实用培训教程》  
    http://202.101.232.120/book/open  ...  name=BC98_CB526.zip

    64.《Delphi高级开发指南》  
    http://www.pcbookcn.com/s10899bo  ...  phi_gjkfzn_for3.rar

    65.《新编  Windows  API参考大全》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/新编Windows_API_参考大全.rar

    66.《Delphi深度历险-附书源码》  
    http://www.pcbookcn.com/s10899bo  ...  elphi_sdlx_code.rar

    67.《Delphi  7高效数据库程序设计》
    ftp://book:book@down.pcbookcn.com/pro/delphi/李维的新书《Delphi7高效数据库程序设计》.rar

    68.《Delphi7开发指南》
    ftp://book:book@down.pcbookcn.com/pro/delphi/delphi7开发指南.rar

    69.《Delphi6集成开发环境》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6集成开发环境.rar

    70.《Delphi6数据库编程》  
    ftp://book:book@down.pcbookcn.com/pro/delphi/Delphi6数据库编程.rar

    72.《Delphi5.xADO_MTS_COM+高级程序设计篇》
    ftp://book:book@down.pcbookcn.co  ...  lphi5.xADO_MTS_COM+高级程序设计篇.rar

    73.《VISUAL  BASIC  编程标准》  
    http://www.dingbing.com/book/vb.zip

    74.《Visual  Basic6.0中文版程序员指南》  
    http://www.easysea.com/diannao/download/prog/vb/zwbc.zip

    75.《Visual  Basic  6.0  控件参考手册》  
    http://www.easysea.com/diannao/download/prog/vb/kjck.zip

    76.《Visual  Basic  6.0中文版语言参考手册》  
    http://www.easysea.com/diannao/download/prog/vb/zwby.zip

    77.《Visual  Basic  6.0  开发宝典》  
    http://www.easysea.com/diannao/download/prog/vb/kfbd.zip

    78.《Visual  Basic  6.0  实例教程》  
    http://www.easysea.com/diannao/download/prog/vb/sljc.zip

    79.《VB  6.0  中文版实用参考手册》  
    http://www.easysea.com/diannao/download/prog/vb/syck.zip

    80.《Visual  Basic  6开发人员指南》  
    http://www.easysea.com/diannao/download/prog/vb/kfzn.zip

    81.《VB  和  SQL  Server  编程指南(第五版)》  
    http://www.easysea.com/diannao/download/prog/vb/bczn.zip

    82.《Jbuilder  5  中文帮助》  
    http://www.pdown.net/download.asp?downid=2&id=991

    83.《JBuilder开发人员指南》  
    http://youth.dlmu.edu.cn/book/list_down.php?bkid=224

    84.《Win32的Internet函数说明》  
    档案大小:  245248K  
    http://www.easysea.com/diannao/download/prog/windows/win32int.zip

    85.《Visual  InterDev  从入门到精通》  
    http://www.easysea.com/diannao/download/prog/interdev/crmd.wdl

    86.《Visual  InterDev  6.0  Web  参考手册  》  
    http://www.easysea.com/diannao/download/prog/interdev/jsck.zip

    87.《Visual  InterDev  6.0  Guide  程序员》
    http://www.easysea.com/diannao/download/prog/interdev/cxyz.zip

    88.《javascript  程序开发手册》  
    http://www.cty99.com/Templet/bookdownmore.asp?booktype=script#

    89.《JAVA  大全》  
    http://www.easysea.com/diannao/download/prog/java/cxkf.zip

    90.《Visual  J++  6.0  WFC  类库参考手册》  
    http://www.easysea.com/diannao/download/prog/java/lkck.zip

    91.《Java联想(中文)》  
    http://www.easysea.com/diannao/download/prog/java/lkck.zip

    92.《Oracle  8  实用大全》
    http://www.easysea.com/diannao/download/prog/oracle/sydq.zip

    93.《Microsoft  SQL  Server  管理员手册》  
    http://www.easysea.com/diannao/download/prog/sql/glys.zip

    94.《掌握ACCESS开发》  
    http://www.easysea.com/diannao/download/prog/sql/glys.zip

    95.《Oracle  Performance  Tuning  and  Optimization》  
    http://www.oradb.net/book/oracle_pt.zip

    96.《Oracle  ProC  程序设计》  
    http://www.oradb.net/book/oracleproc.zip

    97.《Oracle8初学者指南》  
    http://www.easysea.com/diannao/download/prog/oracle/cxzz.zip

    98.《RED  HAT  LINUX  6大全》  
    http://www.dingbing.com/book/redhatall.zip

    99.《RED  HAT  LINUX  6管理工具》  
    http://www.dingbing.com/book/redhatman.zip

    100.《VC++高级编程》  
    http://www.easysea.com/diannao/download/prog/c/vcgj.zip
    posted @ 2006-02-22 22:03 海思 阅读(330) | 评论 (0)编辑 收藏