??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲欧洲国产成人综合在线观看,亚洲人成网站影音先锋播放,337p欧洲亚洲大胆艺术http://m.tkk7.com/mkchen/用开攄脑子去闯?用开阔的视野L?用^和的w心ȝl?用美好的理想去追?zh-cnMon, 12 May 2025 08:56:56 GMTMon, 12 May 2025 08:56:56 GMT60java关于23U设计模式的有趣见解 http://m.tkk7.com/mkchen/archive/2007/01/27/96327.htmlh?/dc:creator>h?/author>Sat, 27 Jan 2007 15:05:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/27/96327.htmlhttp://m.tkk7.com/mkchen/comments/96327.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/27/96327.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/96327.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/96327.html创徏型模?

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

工厂模式Q客L和工厂类分开。消费者Q何时候需要某U品,只需向工厂请求即可。消费者无M改就可以接纳C品。缺Ҏ当品修ҎQ工厂类也要做相应的修改。如Q如何创建及如何向客L提供?

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

建造模式:品的内部表象和品的生成q程分割开来,从而一个徏造过E生成具有不同的内部表象的品对象。徏造模式得品内部表象可以独立的变化Q客户不必知道品内部组成的l节。徏造模式可以强制实行一U分步骤q行的徏造过E?

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

工厂Ҏ模式Q核心工厂类不再负责所有品的创徏Q而是具体创建的工作交给子类dQ成Z个抽象工厂角Ԍ仅负责给出具体工厂类必须实现的接口,而不接触哪一个品类应当被实例化q种l节?

4、PROTOTYPE—跟MM用QQ聊天Q一定要说些深情的话语了Q我搜集了好多肉ȝ情话Q需要时只要copy出来攑ֈQQ里面p了,q就是我的情话prototype了。(100块钱一份,你要不要Q?

原始模型模式Q通过l出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的Ҏ创徏出更多同cd的对象。原始模型模式允许动态的增加或减品类Q品类不需要非得有M事先定的等U结构,原始模型模式适用于Q何的{l构。缺Ҏ每一个类都必配备一个克隆方法?

5、SINGLETON—俺?个漂亮的老婆Q她们的老公都是我,我就是我们家里的老公SigletonQ她们只要说道“老公”,都是指的同一个hQ那是?刚才做了个梦啦,哪有q么好的?

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

l构型模?

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

适配器(变压器)模式Q把一个类的接口变换成客户端所期待的另一U接口,从而原本因接口原因不匚w而无法一起工作的两个c能够一起工作。适配cd以根据参数返q一个合适的实例l客L?

7、BRIDGE—早上碰到MMQ要说早上好Q晚上碰到MMQ要说晚上好Q碰到MMI了件新衣服Q要说你的衣服好漂亮哦,到MM新做的发型,要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”这U问题,自己用BRIDGEl合一下不p?

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

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

合成模式Q合成模式将对象l织到树l构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树l构表示出来。合成模式得客L把一个个单独的成分对象和׃们复合而成的合成对象同{看待?

9、DECORATOR—Maryq完轮到Sarlyq生日,q是不要叫她自己挑了Q不然这个月伙食费肯定玩完,拿出我去q在华山上照的照片Q在背面写上“最好的的礼物,是׃的Fita”,再到街上C品店买了个像框Q卖C品的MM也很漂亮哦)Q再N壁搞术设计的Mike设计了一个漂亮的盒子装v来……,我们都是DecoratorQ最l都在修饰我q个人呀Q怎么P看懂了吗Q?

装饰模式Q装饰模式以对客L透明的方式扩展对象的功能Q是l承关系的一个替代方案,提供比承更多的灉|性。动态给一个对象增加功能,q些功能可以再动态的撤消。增加由一些基本功能的排列l合而生的非常大量的功能?/p>

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

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

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

享元模式QFLYWEIGHT在拳L赛中指最轻量U。n元模式以׃n的方式高效的支持大量的细_度对象。n元模式能做到׃n的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部Q不会随环境的改变而有所不同。外蕴状态是随环境的改变而改变的。外蕴状态不能媄响内蕴状态,它们是相互独立的。将可以׃n的状态和不可以共享的状态从常规cM区分开来,不可以׃n的状态从c里剔除出去。客L不可以直接创׃n的对象,而应当用一个工厂对象负责创׃n的对象。n元模式大q度的降低内存中对象的数量?

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

代理模式Q代理模式给某一个对象提供一个代理对象,q由代理对象控制Ҏ对象的引用。代理就是一个h或一个机构代表另一个h或者一个机构采取行动。某些情况下Q客户不x者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客L分L不出代理主题对象与真实主题对象。代理模式可以ƈ不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,q时候代理对象不能够创徏被代理对象,被代理对象必Lpȝ的其他角色代为创建ƈ传入?

行ؓ模式

13、CHAIN OF RESPONSIBLEITY—晚上去上英语课Qؓ了好开溜坐C最后一排,哇,前面坐了好几个漂亮的MM哎,扑ּU条Q写上“Hi,可以做我的女朋友吗?如果不愿意请向前传”,U条׃个接一个的传上MQ糟p,传到W一排的MM把纸条传l老师了,听说是个老处奛_Q快?

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

h形成一条链。请求在q个链上传递,直到链上的某一个对象决定处理此h。客户ƈ不知道链上的哪一个对象最l处理这个请求,pȝ可以在不影响客户端的情况下动态的重新l织铑֒分配责Q。处理者有两个选择Q承担责L者把责Q推给下家。一个请求可以最l不被Q何接收端对象所接受?
14、COMMAND—俺有一个MM安得特别严,没法见面Q只好借助于她弟弟在我们俩之间传送信息,她对我有什么指C,写一张纸条让她弟弟带l我。这不,她弟弟又传送过来一个COMMANDQؓ了感谢他Q我请他吃了杂酱面Q哪知道他说Q“我同时l我姐姐三个h友送COMMANDQ就C最气Q才h吃面。”,:-(

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

15、INTERPRETER—俺有一个《MM真经》,上面有各UMM的攻略,比如说去吃西的步骤、去看电qҎ{等Q跟MMU会Ӟ只要做一个InterpreterQ照着上面的脚本执行就可以了?

解释器模式:l定一个语a后,解释器模式可以定义出其文法的一U表C,q同时提供一个解释器。客L可以使用q个解释器来解释q个语言中的句子。解释器模式描q怎样在有了一个简单的文法后,使用模式设计解释q些语句。在解释器模式里面提到的语言是指M解释器对象能够解释的Ml合。在解释器模式中需要定义一个代表文法的命ocȝ{l构Q也是一pd的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的{l构中的对象的Q何排列组合都是一个语a?

 

16、ITERATOR—我׃了MaryQ不一切的向她求婚?

MaryQ“想要我跟你l婚Q得{应我的条g?

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

MaryQ“我看上了那个一克拉的钻石?

我:“我乎ͼ我买Q还有吗Q?

MaryQ“我看上了湖边的那栋别墅?

我:“我乎ͼ我买Q还有吗Q?

MaryQ“你的小弟弟必须要有50cm镎?

我脑袋嗡的一壎ͼ坐在椅子上,一咬牙Q“我剪,我剪Q还有吗Q?

…?

q代子模式:q代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起Ş成的MUC集,聚集对象是能够包容一l对象的容器对象。P代子模式P代逻辑装C个独立的子对象中Q从而与聚集本n隔开。P代子模式化了聚集的界面。每一个聚集对象都可以有一个或一个以上的q代子对象,每一个P代子的P代状态可以是彼此独立的。P代算法可以独立于聚集角色变化?

17、MEDIATOR—四个MM打麻,怺之间谁应该给谁多钱不清楚了,q怺当时我在旁边Q按照各自的{码数算钱,赚了q从我q里拿,赔了q也付l我Q一切就OK啦,俺得C四个MM的电话?

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

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

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

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

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

20、STATE—跟MM交往Ӟ一定要注意她的状态哦Q在不同的状态时她的行ؓ会有不同Q比如你U她今天晚上ȝ电媄Q对你没兴趣的MM׃说“有事情啦”,对你不讨厌但q没喜欢上的MM׃说“好啊,不过可以带上我同事么Q”,已经喜欢上你的MM׃说“几炚wQ看完电影再L吧怎么P”,当然你看电媄q程中表现良好的话,也可以把MM的状态从不讨厌不喜欢变成喜欢哦?

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

   21、STRATEGY—跟不同cd的MMU会Q要用不同的{略Q有的请电媄比较好,有的则去吃小吃效果不错,有的LvҎ漫最合适,单目的都是ؓ了得到MM的芳心,我的qMM锦囊中有好多Strategy哦?

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

22、TEMPLATE METHOD——看q《如何说服女生上床》这部经典文章吗Q女生从认识C床的不变的步骤分为y遇、打破僵局、展开q求、接吅R前戏、动手、爱抚、进d大步?Template method)Q但每个步骤针对不同的情况,都有不一L做法Q这p看你随机应变?具体实现)Q?

模板Ҏ模式Q模板方法模式准备一个抽象类Q将部分逻辑以具体方法以及具体构造子的Ş式实玎ͼ然后声明一些抽象方法来q子类实现剩余的逻辑。不同的子类可以以不同的方式实现q些抽象ҎQ从而对剩余的逻辑有不同的实现。先制定一个顶U逻辑框架Q而将逻辑的细节留l具体的子类d现?

23、VISITOR—情CQ要l每个MM送一束鲜花和一张卡片,可是每个MM送的花都要针对她个h的特点,每张卡片也要Ҏ个h的特Ҏ挑,我一个h哪搞得清楚,q是找花店老板和礼品店老板做一下VisitorQ让花店老板ҎMM的特炚w一束花Q让C品店老板也根据每个h特点选一张卡Q这样就L多了Q?

讉K者模式:讉K者模式的目的是封装一些施加于某种数据l构元素之上的操作。一旦这些操作需要修改的话,接受q个操作的数据结构可以保持不变。访问者模式适用于数据结构相Ҏ定的pȝQ它把数据结构和作用于结构上的操作之间的耦合解脱开Q得操作集合可以相对自q演化。访问者模式得增加新的操作变的很ҎQ就是增加一个新的访问者类。访问者模式将有关的行为集中到一个访问者对象中Q而不是分散到一个个的节点类中。当使用讉K者模式时Q要尽可能多的对象览逻辑攑֜讉K者类中,而不是放到它的子cM。访问者模式可以跨q几个类的等U结构访问属于不同的{l构的成员类?/p>

?a >http://java.ccidnet.com/art/3749/20060622/586221_3.html

 



]]>
Object Hierarchy and Inheritance in JavaScripthttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.htmlh?/dc:creator>h?/author>Sun, 21 Jan 2007 08:19:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.htmlhttp://m.tkk7.com/mkchen/comments/95144.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/21/95144.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/95144.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/95144.html

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 . 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 .

    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 , 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



  • ]]>
    JavaScript 语言Ҏ[转]http://m.tkk7.com/mkchen/archive/2007/01/21/95139.htmlh?/dc:creator>h?/author>Sun, 21 Jan 2007 07:49:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/21/95139.htmlhttp://m.tkk7.com/mkchen/comments/95139.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/21/95139.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/95139.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/95139.html

    跨越边界: JavaScript 语言Ҏ?/h1>

    研究~程语言中的“丑鸭?/p> developerWorks
    文档选项
    此作为电子邮件发? src=

    此作为电子邮件发?/font>

    未显C需?JavaScript 的文档选项

    样例代码


    拓展 Tomcat 应用

    下蝲 IBM 开?J2EE 应用服务?WAS CE 新版?V1.1


    U别: 初

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

    2007 q?1 ?18 ?/p>

    JavaScript 常被Z认ؓ是编E语a中无重的一员。这U观点的形成可以“归功”于其开发工兗复杂且不一致的面向 HTML 面的文档对象模型以及不一致的览器实现。但 JavaScript l对不仅仅是一个玩兯么简单。在本文中,Bruce Tate 向您介绍?JavaScript 的语aҎ?

    几乎每个 Web 开发h员都曾有q诅?JavaScript 的经历。这个备受争议的语言受篏于其复杂的称为文档对象模?(DOM)的编E模型、糟p的实现和调试工具以及不一致的览器实现。直到最q,很多开发h员还认ؓ Javascript 从最好的斚w说是无可避免之灾,从最坏的斚w说不q是一U玩LŞ了?

    然?JavaScript 现在开始日益重要v来,而且成ؓ了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏一些业界领袖h物也不得不开始重新审视这U编E语a。诸?Ajax (Asynchronous JavaScript + XML) q样的编E技术让 Web |页更加qh。而完整的 Web 开发框Ӟ比如 Apache CocoonQ则?JavaScript 的应用越来越多,使其不只限于是一U用于制?Web 面的简单脚本。JavaScript 的一U称?ActionScript 的派生物也推动了 Macromedia ?Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino ?JavaScript 成ؓ?Java?开发h员所首选的一c脚本语aQ参?参考资?/font>Q?

    我的好友兼同?Stuart Halloway ?Ajax 斚w的专Ӟ曑֜其教授的 JavaScript 评中做q这L开场白Q“到 2011 q_JavaScript 被公认为是一U拥有开发现代应用程序所需的一整套新特性的语言?。他l而介l说 JavaScript E序要比cM?Java E序紧密十倍,ql展CZ使其之所以如此的一些语aҎ?

    关于q个pd

    ?跨越边界pd?/font>Q作?Bruce Tate 提出了这样一个主张:今天?Java E序员通过学习其他技术和语言Q会得到很好的帮助。编E领域已l发生了变化QJava 技术不再是所有开发项目理所当然的最佳选择。其他框架正在媄?Java 框架构徏的方式,而从其他语言学到的概念也有助?Java ~程。对 PythonQ或 Ruby、Smalltalk {等Q代码的~写可能改变 Java ~码的方式?/p>

    q个pd介绍的编E概念和技术,?Java 开发有Ҏ的不同,但可以直接应用于 Java ~程。在某些情况下,需要集成这些技术来利用它们。在其他情况下,可以直接应用q些概念。单独的工具q不重要Q重要的是其他语a和框架可以媄?Java C֌中的开发h员、框Ӟ甚至是基本方式?

    在这文章中Q我带您探I?JavaScript 的一些特性,看看q些Ҏ如何让它如此具有吸引力Q?

    • 高阶函数Q?/b> 一个高阶函数可以将函数作ؓ参数Q也可以q回一个函数。此Ҏ让 JavaScript E序员可以用 Java 语言所不能提供的方法来操纵函数?br />
    • 动态类型:通过延迟l定QJavaScript 可以更准和更灵zR?br />
    • 灉|的对象模型:JavaScript 的对象模型用一U相对不常见的方式进行?—?UCؓ原型 —?而不?Java 语言中更常见的基于类的对象模型?

    您可能已l熟悉动态类型模型、高阶函数Ş式的函数式编E以及开攑֯象模型这些概念,因ؓ我在其他?i>跨越边界 pd文章中已l作q相关的介绍。如果您从未q行qQ何正式的 JavaScript 开发,您很可能会认些特性属于非常复杂的语言Q例?Python、Lisp、Smalltalk ?HaskellQ而绝非像 JavaScript q样的语a所能提供的。因此,我将用实际的代码CZ来说明这些概c?

    立即开?/span>

    您无需讄 JavaScript。如果您可以在浏览器中阅L文章,p明您已经准备qA了。本文包含的所有编E示例都可以在大多数览器内q行。我使用的是 Firefox?

    用在 <script type='text/javascript'> ?</script> 标记之间所包含?JavaScript 加蝲单的 Web 面。清?1 可以昄 Hello, World 文本Q?



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

    要运行此代码Q只需创徏一个名?example1.html 的文件。将清单 1 的代码复制到该文件内Qƈ在浏览器中加载此文gQ参?下蝲 部分以获得本文用的所有示?HTML 文gQ。注意到每次重蝲此页面时Q该代码都会立即执行?/p>

    alert 是个函数调用Q只有一个字W串作ؓ参数。图 1 昄了由清单 1 中的代码弹出的警告框Q显C文?“Hello, World”。如果代码在 HTML body 之内Q目前ƈ未指定Q?bodyQ但览器能接受不规则的 HTMLQƈ且整个页面都默然作ؓ一?body 被处理)。页面一旦加载,JavaScript ׃立即执行?



    ?1. Hello, world
    Hello, World.

    如果要gq执行,可以?HTML <head> 元素声明 JavaScript 函数Q如清单 2 所C:



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

    清?2 中的代码输入C?HTML 文gQ在览器内加蝲该文Ӟ单击 Say Hello 按钮Q结果如?2 所C:



    ?2. 延迟执行
    延迟执行




    回页?/font>


    高阶函数

    ?清单 2Q可以大致体会到一?JavaScript 在操U函数方面的能力。将函数名称传递给 HTML button 标记q利?HTML 的内|事件模型。?JavaScript Ӟ我会l常在变量或数组中存储函敎ͼ在本文后面的 对象模型 一节,您会看到 JavaScript 对象模型{略大量使用了此技巧)。例如,查看一下清?3Q?



    清单 3. 用变量操U函?/b>
    				
    <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 中的一cd象,可以自由地操U它们。首先我声明两个函数Q?code>hot ?cold。ƈ分别在不同的变量存储它们。单?Hot ?Cold 按钮会调用对应的函数Q生成一个告警。接下来Q声明另一个函数用来交?Hot ?Cold 按钮的|此函数与第三个按钮兌Q该按钮昄如图 3 所C的告警Q?



    ?3. 操纵函数

    q个例子说明可以像处理其他变量一样处理函数。C 开发h员很Ҏ此概念看作?i>函数指针 功能Q但 JavaScript 的高阶函数的功能更ؓ强大。该Ҏ让 JavaScript E序员能够像处理其他变量cd一栯村֤理动作或函数?/p>

    函数用作函数的参数Q或函C为D回,q些概念属于高阶函数的领域。清?4 ?清单 3 做了一点点修改Q显CZ能返回函数的高阶函数Q?/p>

    清单 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>
    

    q个例子解决了一个常见问题:如何更改中的行为附加到用户接口事gQ通过高阶函数Q这很容易做到?code>temperature 高阶函数q回 current 的|?current 又可以有 hot ?cold 函数。看一下这个有些陈旧的函数调用Q?code>temperature()()。第一l括L于调?temperature 函数。第二组括号调用?temperatureq回 的函数。图 4 昄了输出:



    ?4. 高阶函数
    高阶函数

    高阶函数是函数式~程的基Q对比面向对象编E,函数式编E代表了更高U别的抽象。但 JavaScript 的实力ƈ不仅限于高阶函数。JavaScript 的动态类型就极ؓ适合 UI 开发?/p>



    回页?/font>


    动态类?/span>

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

    • 必须提前声明意图Q这常常会导致灵zL降低。例如,更改一?Java cd会更改类的类型,因而必重新编译。对比之下,Ruby 允许开攄c,但更改一?Java c还是会更改cȝcd?br />
    • 要实现相同的功能Q必输入更多的代码。例如,必须用参数Ş式包括进cd信息Q必ȝ函数形式q回值和所有变量的cd。另外,q必d明所有变量ƈ昑ּ地{化类型?br />
    • 静态语a的编?部v周期要比动态语a的部|周期长Q尽一些工具可被用来在某种E度上缓解这一问题?

    静态类型更适合用于构徏中间件或操作pȝ的语a中。UI 开发常帔R要更高的效率和灵zL,所以更适合采用动态类型。我qq种做法存在危险。相信用过 JavaScript ?Web 开发h员都曄为编译器本应到的错误类型的变量而绞脑汁。但它所带来的优势同样不可否认。下面将举例加以说明?/p>

    首先Q考虑一个对象的情况。在清单 5 中,创徏一个新对象Qƈ讉K一个不存在的属性,名ؓ colorQ?/p>

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

    当加载ƈ执行此应用程序时Q会得到如图 5 所C的l果Q?/p>

    ?5. 引入属?/b>
     引入属? src=

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

    可以L地重?清单 5Q其如清单 6 所C:



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

    从上例可以看出,?JavaScript 的不同概念之间可以如此轻村֜来回变换Q其含义上的变化很大 —?比如Q是引入行ؓq是引入数据 —?但语法上的变化却很小。该语言很好的g展性是它的一U优势,但同样也是其~点所在。实际上Q该语言本n的对象模型就?JavaScript 延展E度的一U体现?/p>



    回页?/font>


    对象模型

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

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

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



    清单 7. 创徏一个构造函?/b>
    				
    <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 所C:



    ?6. 创徏一个构造函?/b>
    构造函? src=

    对于 Java 开发h员而言Q清?7 中的代码看v来多有点生疏和奇怪。实际上对于没有亲自构徏q对象的许多 JavaScript 开发h员来_q些代码同样看v来有点生疏和奇怪。也许,下面的解释可以让大家能够更好地理解这D代码?

    实际上,您只需重点x其中三段信息。首先,JavaScript 用嵌套函数表C对象。这意味着清单 7 中的 Animal 的定义是一U有效的语法。第二,JavaScript Z原型或现有的对象的实例来构造对象,而非ZcLѝ?code>funct() 是一U调用,?new Animal() 却基?Animal 内的原型构造一个对象。最后,?JavaScript 中,对象只是函数和变量的集合。每个对象ƈ不与cd相关Q所以可以自由地修改q种l构?

    回到 清单 7。如您所见,JavaScript Z?Animal 中指定的原型定义一个新对象Q?code>myAnimal。而可以用原型中的属性和函数Q甚或重定义函数和属性。这U灵zL可能会?Java 开发h员受不了Q因Z们不习惯q种行ؓQ但它的是一U十分强大的模型?/p>

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



    清单 8. 通过原型l承
    				
    <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 原型。此原型Z Animal?code>Dog 重定?speak() Ҏ但却不会?name() Ҏ做Q何改动。随后,原?Dog 讄?Animal。图 7 昄了其l果Q?/p>

    ?7. 通过原型l承
    l承

    q也展示?JavaScript 是如何解军_属性或Ҏ的引用问题的Q?/p>

    • JavaScript Z原始的原型创建实例,该原型在构造函C定义。Q何对Ҏ或属性的引用都会使用所生成的原始副本?br />
    • 您可以在对象内像定义其他M变量一样重新定义这些变量。这样做必然会更Ҏ对象。所以您昑ּ定义的Q何属性或函数都将比在原始的原型中定义的那些属性或函数优先U要高?br />
    • 如果您显式设|了名ؓ prototype 的实例变量,JavaScript ׃在此实例中寻找Q何未定义的实例变量或属性。这U查找是递归的:如果 ?prototype 内定义的实例不能扑ֈ属性或函数Q它׃?i>?/i> 原型中查找,依此cL?

    那么QJavaScript 的承模型到底是什么样的?q取决于您如何对它进行定义。您需要定义承行Z便可以覆盖它。然而,从本质上ԌJavaScript 更像是一U函数式语言Q而非面向对象的语aQ它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极ؓ灉|、开攑֒强大Q具有全部的反射性。有些h可能会说它太q灵zR而我的忠告则是,按具体作业的需要选择合适的工具?/p>



    回页?/font>


    l束?/span>

    JavaScript 对象模型构徏在该语言的其他功能之上来支持大量的库Q比?DojoQ参?参考资?/font>Q。这U灵zL让每个框架能够以一U精l的方式更改对象模型。在某种E度上,q种灉|性是一U极大的~点。它可以D可怕的互操作性问题(管该语a的灵zL可以部分缓解这些问题)?

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

    最后,JavaScript 优秀的灵zL的让您体会到了一些高阶语a的强大功能。当然您无需选择为每个项目或大多数项目都做这L权衡和折街但了解一U语a的优势和劣势 —?通过参考大量信息,而不仅仅Zq告宣传或公众意?—?会让您可以更好地控制何时需要用以及何时不能用这U语a。当您在修改 JavaScript Web 部件时Q您臛_知道该如何让此语a发挥它最大的优势。请l箋跨越边界吧?/p>

    参考资?

    学习


    ]]>[转]sqlserver?sql~程的几个小常识http://m.tkk7.com/mkchen/archive/2007/01/07/92212.htmlh?/dc:creator>h?/author>Sun, 07 Jan 2007 06:34:00 GMThttp://m.tkk7.com/mkchen/archive/2007/01/07/92212.htmlhttp://m.tkk7.com/mkchen/comments/92212.htmlhttp://m.tkk7.com/mkchen/archive/2007/01/07/92212.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/92212.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/92212.html1、取出刚刚插?删除)的数据SELECT 字段?FROM INSERTED(DELETED)
    2、对于UPDATE实际上是先DELETE然后再INSERT所以如果想得到UPDATE前后的数据|应该先从DELETED取出Q然后从INSERTED取出Q?br />3、IF UPDATE(列名)可以判断更新或插入哪一个字D늚|
    4、@@ROWCOUNT可以判断上一行查询操作得到的列数Q?br />5、给变量赋值用SET @ZQB = 13;
    6、察看是否有W合条g的记录IF EXISTS (SELECT name FROM sysobjects WHERE name = 'reminder' AND type = 'TR');
    7、定义游标,如下Q?br />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--判断是否到最?br />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--删除游标引用



    ]]>
    [转]Acegi?/title><link>http://m.tkk7.com/mkchen/archive/2006/12/27/90397.html</link><dc:creator>h?/dc:creator><author>h?/author><pubDate>Wed, 27 Dec 2006 15:20:00 GMT</pubDate><guid>http://m.tkk7.com/mkchen/archive/2006/12/27/90397.html</guid><wfw:comment>http://m.tkk7.com/mkchen/comments/90397.html</wfw:comment><comments>http://m.tkk7.com/mkchen/archive/2006/12/27/90397.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://m.tkk7.com/mkchen/comments/commentRss/90397.html</wfw:commentRss><trackback:ping>http://m.tkk7.com/mkchen/services/trackbacks/90397.html</trackback:ping><description><![CDATA[ <a >matrixeditor</a> 发表?2005-07-28 11:06:41<br />作?Matrixeditor     来源:BEA dev2dev<br />评论?4 点击?6,815     投票d?8 投票Mh?3<br />关键? <!-- end of div title --><div id="bxzfzhh" class="summary"><div id="zbxdpfh" class="left"></div><div id="bvpnzzj" class="center"><h4>摘要:</h4>Acegi安全pȝQ是一个用于Spring Framework的安全框Ӟ能够和目前流行的Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean ContextQ拦截器和面向接口的~程方式。因此,Acegi安全pȝ能够L地适用于复杂的安全需求?</div><div id="pjxrrtb" class="right"><div id="xhtfbbb" class="help"><h4>工具?/h4><a >本站收藏</a><br /><a onclick="javascript:location. >味书签</a><br /><a >投票评分</a><br /><a >发表评论</a><br /><a title="点击后直接粘贴即? onclick="copyLink();" >复制链接</a><br /></div></div></div><!-- end of summary line --><div id="zthtnnn" class="overflow" id="text">           Acegi安全pȝQ是一个用于Spring Framework的安全框Ӟ能够和目前流行的Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean ContextQ拦截器和面向接口的~程方式。因此,Acegi安全pȝ能够L地适用于复杂的安全需求?br />       安全涉及C个不同的概念Q认证和授权。前者是关于认用户是否实是他们所宣称的n份。授权则是关于确认用h否有允许执行一个特定的操作?br />       在Acegi安全pȝ中,需要被认证的用Ppȝ或代理称?Principal"。Acegi安全pȝ和其他的安全pȝ不同Q它q没有角色和用户l的概念?br />Acegipȝ设计<br />  关键lg<br />      Acegi安全pȝ包含以下七个关键的功能组Ӟ<br />        1 Authentication对象Q包含了PrincipalQCredential和Principal的授权信息。同时还可以包含关于发v认证h的客L其他信息Q如IP地址?br />        2 ContextHolder对象Q用ThreadLocal储存Authentication对象的地斏V?br />        3 AuthenticationManagerQ用于认证ContextHolder中的Authentication对象?br />        4 AccessDecissionManagerQ用于授权一个特定的操作?br />        5 RunAsManagerQ当执行特定的操作时Q用于选择性地替换Authentication对象?br />        6 Secure Object拦截器,用于协调AuthenticationManagerQAccessDecissionManagerQRunAsManager和特定操作的执行?br />        7 ObjectDefinitionSourceQ包含了特定操作的授权定义?br />      q七个关键的功能lg的关pd下图所C(图中灰色部分是关键组ӞQ?br /><br /><br /><b>安全理对象</b><br />       Acegi安全pȝ目前支持两类安全理对象?br />       W一cȝ安全理对象理AOP Alliance的MethodInvocationQ开发h员可以用它来保护Spring容器中的业务对象。ؓ了Spring理的Bean可以作ؓMethodInvocation来用,Bean可以通过ProxyFactoryBean和BeanNameAutoProxyCreator来管理,像在Spring的事务管理一样用?br />       W二cLFilterInvocation。它用过滤器QFilterQ来创徏Qƈ单地包装了HTTP的ServletRequestQServletResponse和FilterChain。FilterInvocation可以用来保护HTTP资源。通常Q开发h员ƈ不需要了解它的工作机Ӟ因ؓ他们只需要将Filter加入web.xmlQAcegi安全pȝ可以工作了?br /><br /><b>安全配置参数</b><br />       每个安全理对象都可以描q数量不限的各种安全认证h。例如,MethodInvocation对象可以描述带有L参数的Q意方法的调用Q而FilterInvocation可以描述L的HTTP URL?br />       Acegi安全pȝ需要记录应用于每个认证h的安全配|参数。例如,对于BankManager.getBalanceQint accountNumberQ方法和BankManager.approveLoanQint applicationNumberQ方法,它们需要的认证h的安全配|很不相同?br />       Z保存不同的认证请求的安全配置Q需要用配|参数。从实现的视角来看,配置参数使用ConfigAttribute接口来表C。Acegi安全pȝ提供了ConfigAttribute接口的一个实玎ͼSecurityConfigQ它把配|参C存ؓ一个字W串?br />       ConfigAttributeDefinitioncLConfigAttribute对象的一个简单的容器Q它保存了和特定h相关的ConfigAttribute的集合?br />       当安全拦截器收到一个安全认证请求时Q需要决定应用哪一个配|参数。换句话_它需要找出应用于q个h的ConfigAttributeDefinition对象。这个查扄q程是由ObjectDefinitionSource接口来处理的。这个接口的主要Ҏ是public ConfigAttributeDefinition getAttributes(Object object)Q其中Object参数是一个安全管理对象。因为安全管理对象包含有认证h的详l信息,所以ObjectDefinitionSource接口的实现类可以从中获得所需的详l信息,以查扄关的ConfigAttributeDefiniton对象?br /><br /><br /><b>Acegi如何工作</b><br />       Z说明Acegi安全pȝ如何工作Q我们设想一个用Acegi的例子。通常Q一个安全系l需要发挥作用,它必d成以下的工作Q?br />      1 首先Q系l从客户端请求中获得Principal和CredentialQ?br />      2 然后pȝ认证Principal和Credential信息Q?br />      3 如果认证通过Q系l取出Principal的授权信息;<br />      4 接下来,客户端发h作请求;<br />      5 pȝҎ预先配置的参数检查Principal对于该操作的授权Q?br />      6 如果授权查通过则执行操作,否则拒绝?br />      那么QAcegi安全pȝ是如何完成这些工作的呢?首先Q我们来看看Acegi安全pȝ的认证和授权的相关类Q?<br />      安全拦截器的抽象基类Q它包含有两个管理类QAuthenticationManager和AccessDecisionManager。AuthenticationManager用于认证ContextHolder中的Authentication对象Q包含了PrincipalQCredential和Principal的授权信息)QAccessDecissionManager则用于授权一个特定的操作?br /><br />      下面来看一个MethodSecurityInterceptor的例子:<br /><pre class="overflow">      <bean id="bankManagerSecurity" <br />                     class="net.sf.acegisecurity.intercept.method.MethodSecurityInterceptor"><br />             <property name="validateConfigAttributes"><br />                    <value>true</value><br />            </property><br />            <property name="authenticationManager"><br />                   <ref bean="authenticationManager"/><br />            </property><br />            <property name="accessDecisionManager"><br />                  <ref bean="accessDecisionManager"/><br />            </property><br />            <property name="objectDefinitionSource"><br />                  <value><br />                     net.sf.acegisecurity.context.BankManager.delete*=<br />                             ROLE_SUPERVISOR,RUN_AS_SERVER<br />                     net.sf.acegisecurity.context.BankManager.getBalance=<br />                             ROLE_TELLER,ROLE_SUPERVISOR,BANKSECURITY_CUSTOMER,RUN_<br />                  </value><br />            </property><br />      </bean> </pre><br />      上面的配|文件中QMethodSecurityInterceptor是AbstractSecurityInterceptor的一个实现类。它包含了两个管理器QauthenticationManager和accessDecisionManager。这两者的配置如下Q?br />      <pre class="overflow"><bean id="authenticationDao" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl"><br />               <property name="dataSource"><ref bean="dataSource"/></property><br />      </bean><br />      <bean id="daoAuthenticationProvider" <br />                     class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider"><br />               <property name="authenticationDao"><ref bean="authenticationDao"/></property><br />      </bean><br />      <bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager"><br />               <property name="providers"><br />                      <list><ref bean="daoAuthenticationProvider"/></list><br />               </property><br />      </bean><br />      <bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/><br />      <bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased"><br />               <property name="allowIfAllAbstainDecisions"><value>false</value></property><br />               <property name="decisionVoters"><br />                      <list><ref bean="roleVoter"/></list><br />               </property><br />      </bean></pre><br /><br />       准备工作做好了,现在我们来看看Acegi安全pȝ是如何实现认证和授权机制的。以使用HTTP BASIC认证的应用ؓ例子Q它包括下面的步骤:<br />       1. 用户dpȝQAcegi从acegisecurity.ui子系l的安全拦截器(如BasicProcessingFilterQ中得到用户的登录信息(包括Principal和CredentialQƈ攑օAuthentication对象Qƈ保存在ContextHolder对象中;<br />       2. 安全拦截器将Authentication对象交给AuthenticationManagerq行w䆾认证Q如果认证通过Q返回带有Principal授权信息的Authentication对象。此时ContextHolder对象的Authentication对象已拥有Principal的详l信息;<br />       3. 用户d成功后,l箋q行业务操作Q?br />       4. 安全拦截器(bankManagerSecurityQ收到客L操作h后,操作请求的数据包装成安全管理对象(FilterInvocation或MethodInvocation对象Q;<br />       5. 然后Q从配置文gQObjectDefinitionSourceQ中d相关的安全配|参数ConfigAttributeDefinitionQ?br />       6. 接着Q安全拦截器取出ContextHolder中的Authentication对象Q把它传递给AuthenticationManagerq行w䆾认证Qƈ用返回值更新ContextHolder的Authentication对象Q?br />       7. Authentication对象QConfigAttributeDefinition对象和安全管理对象(secure ObjectQ交lAccessDecisionManagerQ检查Principal的操作授权;<br />       8. 如果授权查通过则执行客Lh的操作,否则拒绝Q?br /><br /><b>AccessDecisionVoter</b><br />       注意上节的accessDecisionManager是一个AffirmativeBasedc,它对于用h权的投票{略是,只要通过其中的一个授权投检查,卛_通过Q它的allowIfAllAbstainDecisions属性值是falseQ意思是如果所有的授权投票是都是弃权,则通不q授权检查?br />       Acegi安全pȝ包括了几个基于投策略的AccessDecisionManagerQ上节的RoleVoter是其中的一个投策略实玎ͼ它是AccessDecisionVoter的一个子cRAccessDecisionVoter的具体实现类通过投票来进行授权决{,AccessDecisionManager则根据投结果来军_是通过授权查,q是抛出AccessDeniedException例外?br />       AccessDecisionVoter接口共有三个ҎQ?br />public int vote(Authentication authentication, Object object, ConfigAttributeDefinition config);<br />public boolean supports(ConfigAttribute attribute);<br />public boolean supports(Class clazz);<br />       其中的voteҎq回intq回|它们是AccessDecisionVoter的三个静态成员属性:ACCESS_ABSTAIN,QACCESS_DENIED和ACCESS_GRANTEDQ它们分别是弃权Q否军_赞成?br />       Acegi安全pȝ中,使用投票{略的AccessDecisionManager共有三个具体实现c:AffirmativeBased、ConsensusBased和UnanimousBased。它们的投票{略是,AffirmativeBasedcd需有一个投赞成即可通过QConsensusBasedc需要大多数投票赞成卛_通过Q而UnanimousBasedc需要所有的投票赞成才能通过?br />       RoleVotercL一个Acegi安全pȝAccessDecisionVoter接口的实现。如果ConfigAttribute以ROLE_开_RoleVoter则进行投。如果GrantedAuthority的getAutorityҎ的Stringq回值匹配一个或多个以ROLE_开头的ConfigAttributeQ则投票通过Q否则不通过。如果没有以ROLE_开头的ConfigAttributeQRoleVoter则弃权?br /><br /><b>安全拦截?/b><br />  拦截器如何工?br />  MethodInvocation拦截?br />  FilterInvocation拦截?br />认证<br />  认证h<br />  认证理?br />  Authentication Provider<br />授权<br />  Access Decision Manager<br />  Voting Decision Manager<br />  授权理推荐<br />ContextHolder的用h?br />  用户接口目标<br />  HTTP会话认证<br />  HTTP Basic认证<br /><br />1、Log4j的概?br />   Log4j中有三个主要的组Ӟ它们分别是Logger、Appender和LayoutQLog4j 允许开发h员定义多个LoggerQ每个Logger拥有自己的名字,Logger之间通过名字来表明隶属关pR有一个LoggerUCؓRootQ它永远 存在Q且不能通过名字索或引用Q可以通过Logger.getRootLogger()Ҏ获得Q其它Logger通过 Logger.getLogger(String name)Ҏ?br />   Appender则是用来指明所有的log信息存放C么地方,Log4j中支持多UappenderQ如 console、files、GUI components、NT Event Loggers{,一个Logger可以拥有多个AppenderQ也是你既可以Log信息输出到屏q,同时存储C个文件中?br />   Layout的作用是控制Log信息的输出方式,也就是格式化输出的信息?br />   Log4j中将要输出的Log信息定义?U别,依次为DEBUG、INFO、WARN、ERROR和FATALQ当输出Ӟ只有U别高过配置中规定的 U别的信息才能真正的输出Q这样就很方便的来配|不同情况下要输出的内容Q而不需要更改代码,q点实在是方便啊?br /><br />2、Log4j的配|文?br />  虽然可以不用配置文gQ而在E序中实现配|,但这U方法在如今的系l开发中昄是不可取的,能采用配|文件的地方一定一定要用配|文件。Log4j支持?U格式的配置文gQXML格式和Java的property格式Q本人更喜欢后者,首先看一个简单的例子吧,如下Q?br /><br /><pre class="overflow"> log4j.rootLogger=debug, stdout, R<br />  log4j.appender.stdout=org.apache.log4j.ConsoleAppender<br />  log4j.appender.stdout.layout=org.apache.log4j.PatternLayout<br /><br />  # Pattern to output the caller's file name and line number.<br />  log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n<br /><br />  log4j.appender.R=org.apache.log4j.RollingFileAppender<br />  log4j.appender.R.File=example.log<br />  log4j.appender.R.MaxFileSize=100KB<br /><br />  # Keep one backup file<br />  log4j.appender.R.MaxBackupIndex=1<br /><br />  log4j.appender.R.layout=org.apache.log4j.PatternLayout<br />  log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n</pre>         <br /><br />  首先Q是讄rootQ格式ؓ log4j.rootLogger=[level],appenderName, ...Q其中level是讄需要输Z息的U别Q后面是appender的输出的目的圎ͼappenderName是指定日志信息输出到哪个地斏V您可以同时指定多个输出目的地。配|日志信息输出目的地AppenderQ其语法?br />  log4j.appender.appenderName = fully.qualified.name.of.appender.class<br />  log4j.appender.appenderName.option1 = value1<br />  ...<br />  log4j.appender.appenderName.option = valueN<br />Log4j提供的appender有以下几U:<br />  org.apache.log4j.ConsoleAppenderQ控制台Q?br />  org.apache.log4j.FileAppenderQ文Ӟ<br />  org.apache.log4j.DailyRollingFileAppenderQ每天生一个日志文Ӟ<br />  org.apache.log4j.RollingFileAppenderQ文件大到达指定尺寸的时候生新文gQ?br />  org.apache.log4j.WriterAppenderQ将日志信息以流格式发送到L指定的地方)<br />配置日志信息的格式(布局Q,其语法ؓQ?br />  log4j.appender.appenderName.layout = fully.qualified.name.of.layout.class<br />  log4j.appender.appenderName.layout.option1 = value1<br />  ....<br />  log4j.appender.appenderName.layout.option = valueN<br />Log4j提供的layout有以下几U:<br />  org.apache.log4j.HTMLLayoutQ以HTML表格形式布局Q,<br />  org.apache.log4j.PatternLayoutQ可以灵zd指定布局模式Q,<br />  org.apache.log4j.SimpleLayoutQ包含日志信息的U别和信息字W串Q,<br />  org.apache.log4j.TTCCLayoutQ包含日志生的旉、线E、类别等{信息) <br /><br />3、Log4j在程序中的?br />  要在自己的类中用Log4jQ首先声明一个静态变量Logger logger=Logger.getLog("classname")Q在使用之前Q用PropertyConfigurator.configure ("配置文g")配置一下,现在可以用了Q用法如下:logger.debug("debug message")或者logger.info("info message")Q看下面一个小例子Q?br /><br /><pre class="overflow"> import com.foo.Bar;<br />  import org.apache.log4j.Logger;<br />  import org.apache.log4j.PropertyConfigurator;<br />  public class MyApp {<br />    static Logger logger = Logger.getLogger(MyApp.class.getName());<br />    public static void main(String[] args) {<br />      // BasicConfigurator replaced with PropertyConfigurator.<br />      PropertyConfigurator.configure(args[0]);<br />      logger.info("Entering application.");<br />      Bar bar = new Bar();<br />      bar.doIt();<br />      logger.info("Exiting application.");<br />    }<br />  }</pre><br /><br /><br />[介]<br /><br />对于一个典型的Web应用Q完善的认证和授权机制是必不可少的,在SpringFramework中,Juergen Hoeller提供的范例JPetStorel了一些这斚w的介l,但还q远不够QAcegi是一个专门ؓSpringFramework提供安全机制?目Q全UCؓAcegi Security System for SpringQ当前版本ؓ0.5.1Q就其目前提供的功能Q应该可以满绝大多数应用的需求?br /><br />本文的主要目的是希望能够说明如何在基于Spring构架的Web应用中用AcegiQ而不是详l介l其中的每个接口、每个类。注意,即对已l存在的Spring应用Q通过下面介绍的步骤,也可以马上n受到Acegi提供的认证和授权?br /><br />[基础工作]<br />在你的Web应用的lib中添加Acegi下蝲包中的acegi-security.jar<br /><br />[web.xml]<br />实现认证和授权的最常用的方法是通过filterQAcegi亦是如此Q通常Acegi需要在web.xmld以下5个filter:<br /><br /><pre class="overflow"><filter><br />  <filter-name>Acegi Channel Processing Filter</filter-name><br />  <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class><br />  <init-param><br />    <param-name>targetClass</param-name><br />    <param-value>net.sf.acegisecurity.securechannel.ChannelProcessingFilter</param-value><br />  </init-param><br /></filter><br /><filter><br />  <filter-name>Acegi Authentication Processing Filter</filter-name><br />  <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class><br />  <init-param><br />    <param-name>targetClass</param-name><br />    <param-value>net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter</param-value><br />  </init-param><br /></filter><br /><filter><br />  <filter-name>Acegi HTTP BASIC Authorization Filter</filter-name><br />  <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class><br />  <init-param><br />    <param-name>targetClass</param-name><br />    <param-value>net.sf.acegisecurity.ui.basicauth.BasicProcessingFilter</param-value><br />  </init-param><br /></filter><br /><filter><br />  <filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name><br />  <filter-class>net.sf.acegisecurity.ui.AutoIntegrationFilter</filter-class><br /></filter><br /><filter><br />  <filter-name>Acegi HTTP Request Security Filter</filter-name><br />  <filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class><br />  <init-param><br />    <param-name>targetClass</param-name><br />    <param-value>net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter</param-value><br />  </init-param><br /></filter></pre><br /><br />最先引赯惑的是net.sf.acegisecurity.util.FilterToBeanProxyQAcegi自己的文档上解释是: “What  FilterToBeanProxy does is delegate the Filter's methods through to a bean which is obtained from the <br />Spring application context. This enables the bean to benefit from the Spring application context lifecycle support and configuration flexibility.”,如希望深I的话,ȝ看源代码应该不难理解?br /><br />再下来就是添加filter-mapping了:<br /><pre class="overflow"><filter-mapping><br />  <filter-name>Acegi Channel Processing Filter</filter-name><br />  <url-pattern>/*</url-pattern><br /></filter-mapping><br /><filter-mapping><br />  <filter-name>Acegi Authentication Processing Filter</filter-name><br />  <url-pattern>/*</url-pattern><br /></filter-mapping><br /><filter-mapping><br />  <filter-name>Acegi HTTP BASIC Authorization Filter</filter-name><br />  <url-pattern>/*</url-pattern><br /></filter-mapping><br /><filter-mapping><br />  <filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name><br />  <url-pattern>/*</url-pattern><br /></filter-mapping><br /><filter-mapping><br />  <filter-name>Acegi HTTP Request Security Filter</filter-name><br />  <url-pattern>/*</url-pattern><br /></filter-mapping></pre><br /><br />q里Q需要注意以下两点:<br />1) q几个filter的顺序是不能更改的,序不对无法正常工作;<br />2) 如果你的应用不需要安全传输,如httpsQ则?Acegi Channel Processing Filter"相关内容注释掉即可;<br />3) 如果你的应用不需要Spring提供的远E访问机Ӟ如Hessian and BurlapQ将"Acegi HTTP BASIC Authorization <br />Filter"相关内容注释掉即可?br /><br />[applicationContext.xml]<br />接下来就是要dapplicationContext.xml中的内容了,从刚才FilterToBeanFactory的解释可以看出,真正的filter?br />在Spring的applicationContext中管理:<br /><br />1) 首先Q你的数据库中必d有保存用户名和密码的tableQAcegi要求table的schema必须如下Q?br /><br /><pre class="overflow">CREATE TABLE users (<br />    username VARCHAR(50) NOT NULL PRIMARY KEY,<br />    password VARCHAR(50) NOT NULL,<br />    enabled BIT NOT NULL<br />);<br />CREATE TABLE authorities (<br />    username VARCHAR(50) NOT NULL,<br />    authority VARCHAR(50) NOT NULL<br />);<br />CREATE UNIQUE INDEX ix_auth_username ON authorities ( username, authority );<br />ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users foreign key (username) REFERENCES users<br />(username);</pre><br /><br />2) d讉K你的数据库的datasource和Acegi的jdbcDaoQ如下:<br /><br /><pre class="overflow"><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><br />  <property name="driverClassName"><value>${jdbc.driverClassName}</value></property><br />  <property name="url"><value>${jdbc.url}</value></property><br />  <property name="username"><value>${jdbc.username}</value></property><br />  <property name="password"><value>${jdbc.password}</value></property><br /></bean><br /><bean id="jdbcDaoImpl" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl"><br />  <property name="dataSource"><ref bean="dataSource"/></property><br /></bean></pre><br /><br />3) dDaoAuthenticationProvider:<br /><br /><pre class="overflow"><bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider"><br />  <property name="authenticationDao"><ref bean="authenticationDao"/></property><br />  <property name="userCache"><ref bean="userCache"/></property><br /></bean><br /><br /><bean id="userCache" class="net.sf.acegisecurity.providers.dao.cache.EhCacheBasedUserCache"><br />  <property name="minutesToIdle"><value>5</value></property><br /></bean></pre><br /><br />如果你需要对密码加密Q则在daoAuthenticationProvider中加入:<property name="passwordEncoder"><ref <br />bean="passwordEncoder"/></property>QAcegi提供了几U加密方法,详细情况可看?br />net.sf.acegisecurity.providers.encoding<br /><br />4) dauthenticationManager:<br /><br /><pre class="overflow"><bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager"><br />  <property name="providers"><br />    <list><br />      <ref bean="daoAuthenticationProvider"/><br />    </list><br />   </property><br /></bean></pre><br /><br />5) daccessDecisionManager:<br /><br /><pre class="overflow"><bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased"><br />  <property name="allowIfAllAbstainDecisions"><br />    <value>false</value><br />  </property><br />  <property name="decisionVoters"><br />    <list><ref bean="roleVoter"/></list><br />  </property><br /></bean><br /><bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/></pre><br /><br />6) dauthenticationProcessingFilterEntryPoint:<br /><br /><pre class="overflow"><bean id="authenticationProcessingFilterEntryPoint" <br />class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint"><br />  <property name="loginFormUrl"><value>/acegilogin.jsp</value></property><br />  <property name="forceHttps"><value>false</value></property><br /></bean></pre><br /><br />其中acegilogin.jsp是登陆页面,一个最单的d面如下Q?br /><br /><pre class="overflow"><%@ taglib prefix='c' uri='http://java.sun.com/jstl/core' %><br /><%@ page import="net.sf.acegisecurity.ui.AbstractProcessingFilter" %><br /><%@ page import="net.sf.acegisecurity.AuthenticationException" %><br /><html><br />  <head><br />    <title>Login</title><br />  </head><br /><br />  <body><br />    <h1>Login</h1><br />    <form action="<c:url value='j_acegi_security_check'/>" method="POST"><br />      <table><br />        <tr><td>User:</td><td><input type='text' name='j_username'></td></tr><br />        <tr><td>Password:</td><td><input type='password' name='j_password'></td></tr><br />        <tr><td colspan='2'><input name="submit" type="submit"></td></tr><br />        <tr><td colspan='2'><input name="reset" type="reset"></td></tr><br />      </table><br />    </form><br />  </body><br /></html></pre><br /><br />7) dfilterInvocationInterceptor:<br /><br /><pre class="overflow"><bean id="filterInvocationInterceptor" <br />class="net.sf.acegisecurity.intercept.web.FilterSecurityInterceptor"><br />  <property name="authenticationManager"><br />    <ref bean="authenticationManager"/><br />  </property><br />  <property name="accessDecisionManager"><br />    <ref bean="accessDecisionManager"/><br />  </property><br />  <property name="objectDefinitionSource"><br />    <value><br />      CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON<br />      \A/sec/administrator.*\Z=ROLE_SUPERVISOR<br />      \A/sec/user.*\Z=ROLE_TELLER<br />    </value><br />  </property><br /></bean></pre><br /><br />q里h意,要objectDefinitionSource中定义哪些页面需要权限访问,需要根据自q应用需求进行修改,我上面给?br />的定义的意思是q样的:<br />a. CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON意思是在比较请求\径时全部转换为小?br />b. \A/sec/administrator.*\Z=ROLE_SUPERVISOR意思是只有权限为ROLE_SUPERVISOR才能讉K/sec/administrator*的页?br />c. \A/sec/user.*\Z=ROLE_TELLER意思是只有权限为ROLE_TELLER的用h能访?sec/user*的页?br /><br />8) dsecurityEnforcementFilter:<br /><br /><pre class="overflow"><bean id="securityEnforcementFilter" class="net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter"><br />  <property name="filterSecurityInterceptor"><br />    <ref bean="filterInvocationInterceptor"/><br />  </property><br />  <property name="authenticationEntryPoint"><br />    <ref bean="authenticationProcessingFilterEntryPoint"/><br />  </property><br /></bean></pre><br /><br />9) dauthenticationProcessingFilter:<br /><br /><pre class="overflow"><bean id="authenticationProcessingFilter" <br />class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter"><br />  <property name="authenticationManager"><br />    <ref bean="authenticationManager"/><br />  </property><br />  <property name="authenticationFailureUrl"><br />    <value>/loginerror.jsp</value><br />  </property><br />  <property name="defaultTargetUrl"><br />    <value>/</value><br />  </property><br />  <property name="filterProcessesUrl"><br />    <value>/j_acegi_security_check</value><br />  </property><br /></bean></pre><br />其中authenticationFailureUrl是认证失败的面?br /><br />10) 如果需要一些页面通过安全通道的话Q添加下面的配置:<br /><br /><pre class="overflow"><bean id="channelProcessingFilter" class="net.sf.acegisecurity.securechannel.ChannelProcessingFilter"><br />  <property name="channelDecisionManager"><br />    <ref bean="channelDecisionManager"/><br />  </property><br />  <property name="filterInvocationDefinitionSource"><br />    <value><br />      CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON<br />      \A/sec/administrator.*\Z=REQUIRES_SECURE_CHANNEL<br />      \A/acegilogin.jsp.*\Z=REQUIRES_SECURE_CHANNEL<br />      \A/j_acegi_security_check.*\Z=REQUIRES_SECURE_CHANNEL<br />      \A.*\Z=REQUIRES_INSECURE_CHANNEL<br />    </value><br />  </property><br /></bean><br /><br /><bean id="channelDecisionManager" class="net.sf.acegisecurity.securechannel.ChannelDecisionManagerImpl"><br />  <property name="channelProcessors"><br />    <list><br />      <ref bean="secureChannelProcessor"/><br />      <ref bean="insecureChannelProcessor"/><br />    </list><br />  </property><br /></bean><br /><bean id="secureChannelProcessor" class="net.sf.acegisecurity.securechannel.SecureChannelProcessor"/><br /><bean id="insecureChannelProcessor" class="net.sf.acegisecurity.securechannel.InsecureChannelProcessor"/></pre><br /><br />[~少了什么?]<br />Acegi目前提供了两U?secure object"Q分别对面和方法进行安全认证管理,我这里介l的只是利用<br />FilterSecurityInterceptor对访问页面的权限控制Q除此之外,Acegiq提供了另外一个Interceptor―?br />MethodSecurityInterceptorQ它l合runAsManager可实现对对象中的Ҏ的权限控Ӟ使用Ҏ可参看Acegi自带的文?br />和contact范例?br /><br />[最后要说的]<br />本来以ؓ只是说明如何使用Acegi而已Q应该非常简单,但真正写h才发现想要条理清楚的理顺所有需要的beanq是?br />困难的,但愿我没有遗漏太多东西,如果我的文章有什么遗漏或错误的话Q还请参看Acegi自带的quick-start范例Q但?br />注意Q这个范例是不能直接拿来用的?br />分析和学习Spring中的jpetstore用户理 <br />  存在用户的系l,必然需要用Ld和认证,今天通过分析Spring中自带的jpetstore的例子来学习一下如何实现在Spring构架的系l中用户d?br />1、首先从注册用户开始,先看看jpetstore-servlet.xml中关于注册用Lbean定义Q从定义命名中就可以看出下面q段是注册用户的:<br />  <pre class="overflow"><bean name="/shop/newAccount.do" class="org.springframework.samples.jpetstore.web.spring.AccountFormController"><br />    <property name="petStore"><ref bean="petStore"/></property><br />    <property name="validator"><ref bean="accountValidator"/></property><br />    <property name="successView"><value>index</value></property><br />  </bean></pre><br />1). formView呢?从AccountFormController的构造函C得到Q原来ؓEditAccountFormQ ?br />2). EditoAccountForm.jsp中显得非ؕQ其实没有多难理解的地方,最主要的是q个form既是d新用LQ又是编辑用户信息的Q所以显得有点ؕp糟的?br />2、添加好了新用户Q接下来看看如何dQ在jpetstore-servlet中发现这两个相关bean定义Q如下:<br />  <pre class="overflow"><bean name="/shop/signon.do" class="org.springframework.samples.jpetstore.web.spring.SignonController"><br />    <property name="petStore"><ref bean="petStore"/></property><br />  </bean><br />  <bean name="/shop/signonForm.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController"><br />    <property name="viewName"><value>SignonForm</value></property><br />  </bean></pre><br />1). W二个bean是在q行时用戯入用户名和密码的formQ叫做SignonFormQ对于这?ParameterizableViewControllerQ用文档里的话说q是最单的ControllerQ其作用是在运行中指向 Controller而不是直接指向jsp文gQ仅此而已?br />2). SignonForm.jspQ里面就是一个简单的formQ其action是W一个beanQ即/shop/signon.doQ最需要注意的?signonForwardActionQ其主要作用是forward到需要输入用户名和密码的那个面上去Q这个变量哪里来的呢Q看看下面:<br />  <pre class="overflow"><bean id="secureHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><br />    <property name="interceptors"><br />      <list><br />        <ref bean="signonInterceptor"/><br />      </list><br />    </property><br />    <property name="urlMap"><br />      <map><br />        <entry key="/shop/editAccount.do"><ref local="secure_editAccount"/></entry><br />        <entry key="/shop/listOrders.do"><ref local="secure_listOrders"/></entry><br />        <entry key="/shop/newOrder.do"><ref local="secure_newOrder"/></entry><br />        <entry key="/shop/viewOrder.do"><ref local="secure_viewOrder"/></entry><br />      </map><br />    </property><br />  </bean></pre><br />  原来Q上面的signonInterceptor实现了preHandleQ因此在h上面的map面Ӟ首先要经q这个InterceptorQ看?SignonInterceptor的源码,原来在其中ؓsignon.jsp赋予一个signonForwardAction对象Q呵呵,ȝ明白了?br />3). 接下来去学习一下SignonControllerQ其M部分中可以看出,首先取出用户输入的username和passwordQ然后到数据库中验证 有没有这个用P如果没有q个用户Q返回各错误面Q如果成功,首先生成一个UserSession对象Q在request的session加入q个 userSessionQ注意这部分代码中给ZPagedListHolder分页的简单用方法,关于分页昄Q以后再学习吧?br />3、登录成功后Q就可以Ҏ不同的用戯施不同的行ؓ了,取得用户信息Q无非就是从session取出userSession卛_?br /></div><img src ="http://m.tkk7.com/mkchen/aggbug/90397.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://m.tkk7.com/mkchen/" target="_blank">h?/a> 2006-12-27 23:20 <a href="http://m.tkk7.com/mkchen/archive/2006/12/27/90397.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> [转]软g试工程师面试问?http://m.tkk7.com/mkchen/archive/2006/12/24/89795.htmlh?/dc:creator>h?/author>Sun, 24 Dec 2006 14:49:00 GMThttp://m.tkk7.com/mkchen/archive/2006/12/24/89795.htmlhttp://m.tkk7.com/mkchen/comments/89795.htmlhttp://m.tkk7.com/mkchen/archive/2006/12/24/89795.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/89795.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/89795.html或许你正需要面试Y件测试工E师Q或怽准备d聘Y件测试工E师Q以下是一些可能注意的问题。(选译Q?br />
    有什么原因让你参与到试和质量管理中来?
    什么是试生命周期Q解释一下它的各个阶D?
    试和质量保证有什么不同?
    什么是Negative试Q?
    在之前做试的过E总遇到过哪些问题Q你是如何解决的Q?
    你是如何l你的测试和质量保证团队力量的?
    你是如何定义质量理的?
    你最喜欢试和质量管理什么地方?
    你最不喜Ƣ什么地方?
    什么是瀑布式开发方法,你是否认同所有的步骤Q?
    什么是V-模式开发方法,你是否认同这个模型?
    什么是CMMQ你工作q的公司的别是怎么LQ?
    什么才好的测试h员?

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

    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.

    Q该文{载自MatrixQ原文地址Q?a >http://www.matrix.org.cn/resource/article/44/44430_software+test.htmlQ?/p>

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



    ]]>
    [转]Java 5.0多线E编E?http://m.tkk7.com/mkchen/archive/2006/12/24/89792.htmlh?/dc:creator>h?/author>Sun, 24 Dec 2006 14:37:00 GMThttp://m.tkk7.com/mkchen/archive/2006/12/24/89792.htmlhttp://m.tkk7.com/mkchen/comments/89792.htmlhttp://m.tkk7.com/mkchen/archive/2006/12/24/89792.html#Feedback1http://m.tkk7.com/mkchen/comments/commentRss/89792.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/89792.html阅读全文

    ]]>
    利用XMLBean轻轻松松dXMLhttp://m.tkk7.com/mkchen/archive/2006/12/21/89382.htmlh?/dc:creator>h?/author>Thu, 21 Dec 2006 15:10:00 GMThttp://m.tkk7.com/mkchen/archive/2006/12/21/89382.htmlhttp://m.tkk7.com/mkchen/comments/89382.htmlhttp://m.tkk7.com/mkchen/archive/2006/12/21/89382.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/89382.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/89382.html 利用XMLBean轻轻松松dXML
    作者:叶枫




    版权声明Q本文可以自p{载,转蝲时请务必以超链接形式标明文章原始出处和作者信息及本声?/span>
    作?叶枫(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应用E序里变得越来越重要, q泛应用于数据存储和
    交换. 比如我们常见的配|文?都是以XML方式存储? XMLq应?br />于Java Message Service和Web Services{技术作为数据交?
    因此,正确dXML文档是XML应用的基.
      Java提供了SAX和DOM两种方式用于解析XML,但即便如?要读写一?br />E微复杂的XML,也不是一件容易的?

    二、XMLBean?/span>

        Hibernate已经成ؓ目前行的面向Java环境的对?关系数据库映工?
    在Hibernate{对?关系数据库映工具出C?Ҏ据库的操作是
    通过JDBC来实现的,Ҏ据库的Q何操?开发h员都要自己写SQL语句
    来实? 对象/关系数据库映工具出现后,Ҏ据库的操作{成对
    JavaBean的操?极大方便了数据库开? 所以如果有一个类似的工具能够
    实现对XML的读写{成对JavaBean的操?会化XML的读?即对XML
    不熟悉的开发h员也能方便地dXML. q个工具是XMLBean.

    三、准备XMLBean和XML文档

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


    另外q要准备一个XML文档(customers.xml),
    在本文的例子?我们对q个文档q行d操作. 文档源码如下:

    <?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>


    q是一个客L数据模型,每个客户都有客户~号(ID),姓名,性别(gender),
    电话L(phoneNumber)和地址,其中地址有两? 首要地址(PrimaryAddress)
    和帐单地址(BillingAddress),每个地址有邮~?地址1,和地址2l成.
    其中帐单地址q有收g?receiver).

        此外,q要准备一个配|文?文g名customer.xsdconfig),q个文g?br />作用我后面会?它的内容如下:

    <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环境的对?关系数据库映工L使用步骤一?
    在正式用XMLBean?我们要作两个准备.

        1. 生成XML Schema文g

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

           Z么需要这个文? XMLBean需要通过q个文g知道一个XML文g?br />       l构以及U束,比如数据cd{? 利用q个Schema文g,XMLBean会产生
           一pd相关的Java Classes来实现对XML的操? 而作为开发h?则是
           利用XMLBean产生的Java Classes来完成对XML的操作而不需要SAX或DOM.

           怎样产生q个Schema文g? 如果对于熟悉XML的开发h?可以自己?br />       写这个Schema文g,对于不熟悉XML的开发h?可以通过一些工h完成.
           比较有名的如XMLSPY和Stylus Studio都可以通过XML文g来生成Schema
           文g. 加入我们已经生成q个Schema文g(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的目录下. 通过q个工具,
           我们可以以上的Schema文g生成Java Classes.
           scomp的语法如?-

          

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


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

           在本?我是q样q行?
          

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


           q个命o行的意思是告诉scomp生成customerXmlBean.jar,攑֜build目录?同时
           生成源代码放在build\src? Schema文g是customer.xsd,xsdconfig文g是customer.xsdconfig.

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

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


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

    五、利用XMLBean读XML文g

        新徏一个Java Project,XMLBean2.0.0\lib\下的Jar文g和刚才我们生成的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();
        }

        }
        


        q行?参看输出l果:
        

           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
        

        怎么?是不是很L? XMLBean的威?

    六、利用XMLBean写XML文g

        利用XMLBean创徏一个XML文档也是一件轻而易丄?我们再增加一个Method,
        L一下的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();
        }
        

        q行,打开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文g

        我们再增加一个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");
        }
        

        q行之后,我们会看到客户~号?的客Llastname已经改ؓ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);
        }

            
    q行,我们会看到客户~号?的客L资料已经被删?

    九、查询XML

        除了本文在以上讲q的,利用XMLBean能轻L村֮成XML的读写操作外,l合XPath和XQuery,
       XMLBeanq能完成象SQL查询数据库一h便地查询XML数据. 关于XML查询以及如何创徏XML数据? 我将在另一文章里讨论.



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


    关于作者:
    叶枫Q热爱Java和Oracle. 在Y件开发有q?0q? 目前在国外一家美国大公司担QSA, 负责技术研I。作者BlogQ?a target="_new">http://blog.matrix.org.cn/page/叶枫

    ]]>
    ~写你自q单点dQSSOQ服?/title><link>http://m.tkk7.com/mkchen/archive/2006/12/21/89377.html</link><dc:creator>h?/dc:creator><author>h?/author><pubDate>Thu, 21 Dec 2006 14:42:00 GMT</pubDate><guid>http://m.tkk7.com/mkchen/archive/2006/12/21/89377.html</guid><wfw:comment>http://m.tkk7.com/mkchen/comments/89377.html</wfw:comment><comments>http://m.tkk7.com/mkchen/archive/2006/12/21/89377.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://m.tkk7.com/mkchen/comments/commentRss/89377.html</wfw:commentRss><trackback:ping>http://m.tkk7.com/mkchen/services/trackbacks/89377.html</trackback:ping><description><![CDATA[     摘要: 作者的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摘要Q单点登录(SSOQ的技术被来广泛地q用到各个领域的软gpȝ当中。本...  <a href='http://m.tkk7.com/mkchen/archive/2006/12/21/89377.html'>阅读全文</a><img src ="http://m.tkk7.com/mkchen/aggbug/89377.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://m.tkk7.com/mkchen/" target="_blank">h?/a> 2006-12-21 22:42 <a href="http://m.tkk7.com/mkchen/archive/2006/12/21/89377.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>java实现?8位n份证格式验证法http://m.tkk7.com/mkchen/archive/2006/12/21/89366.htmlh?/dc:creator>h?/author>Thu, 21 Dec 2006 13:47:00 GMThttp://m.tkk7.com/mkchen/archive/2006/12/21/89366.htmlhttp://m.tkk7.com/mkchen/comments/89366.htmlhttp://m.tkk7.com/mkchen/archive/2006/12/21/89366.html#Feedback0http://m.tkk7.com/mkchen/comments/commentRss/89366.htmlhttp://m.tkk7.com/mkchen/services/trackbacks/89366.html
      2、出生日期码表示~码对象出生的年、月、日Q按GB/T7408的规定执行。年、月、日代码之间不用分隔W。例Q某人出生日期ؓ1966q?0?6日,其出生日期码?9661026?br />
      3、顺序码表示在同一地址码所标识的区域范围内Q对同年、同月、同日出生的人编定的序P序码的奇数分配l男性,偶数千分配给x?br />
      4、校验码校验码采用ISO7064Q?983QMOD11-2校验码系l?br />
      1Q十七位数字本体码加权求和公式 S=Sum(Ai*Wi),i=0,...,16Q先对前17位数字的权求和 Ai:表示Wi位置上的w䆾证号码数字倹{Wi:表示Wi位置上的加权因子 Wi:7910584216379105842

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

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

      下面是java实现的代?br />
      /**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;}

      }

      试代码Q用的单元试工具是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());}}


    ]]>
    վ֩ģ壺 99þ99þѾƷС˵| ձվ| 2019ĻѵӰ߲| ĻƵ߹ۿ | ޹Ƭ߲| ޸޵| ձþһva| Ҹ24p| tomӰԺ޹һ| AVһַ | Ļ˾Ʒ| ʮ˽߹ۿƵ| 88avѹۿ| Ƭ߹ۿ | һ߹ۿ | ƵƷ| ˴ֳսŮ2021ƷƵ | պƷһҳ| պƷһAVۿ | ɫվWWW| ¶ۺƵ| ŮaëƬѹۿ| 91ƬýѰӣ| պѸƵ| ޹㽶| ۺa| 69ƵƬ| ޹Ʒ| ۺһ| ۲Ƶwwwѹۿ | ޶Ƶ˵ӰԺ| ɫŮ18ŮëƬƵ | þþ99Ʒѹۿ| һɫëƬ| ˾þô߽| ˮwww| ߾ƷƵ| ޵һ˵| һƵ| 㻨߹ۿѹۿ| avh˶ڵ |