ï»??xml version="1.0" encoding="utf-8" standalone="yes"?>影音先锋中文字幕一区二区,免费观看久久av,亚洲缚视频在线观看http://www.aygfsteel.com/mkchen/用开攄¡š„脑子去闯è?用开阔的视野åŽÀL‹¼æ?用åã^和的íw«å¿ƒåŽÈ£¨¾l?用美好的理想去追æ±?zh-cnTue, 08 Jul 2025 11:42:04 GMTTue, 08 Jul 2025 11:42:04 GMT60java关于23¿Uè®¾è®¡æ¨¡å¼çš„æœ‰è¶£è§è§£ http://www.aygfsteel.com/mkchen/archive/2007/01/27/96327.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sat, 27 Jan 2007 15:05:00 GMThttp://www.aygfsteel.com/mkchen/archive/2007/01/27/96327.htmlhttp://www.aygfsteel.com/mkchen/comments/96327.htmlhttp://www.aygfsteel.com/mkchen/archive/2007/01/27/96327.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/96327.htmlhttp://www.aygfsteel.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Œè€Œæ˜¯ž®†å…·ä½“创建的工作交给子类åŽÕdšåQŒæˆä¸ÞZ¸€ä¸ªæŠ½è±¡å·¥åŽ‚è§’è‰ÔŒ¼Œä»…负责给出具体工厂类必须实现的接口,而不接触哪一个äñ”品类应当被实例化˜q™ç§¾l†èŠ‚ã€?

4、PROTOTYPE—跟MM用QQ聊天åQŒä¸€å®šè¦è¯´äº›æ·±æƒ…的话语了åQŒæˆ‘搜集了好多肉éºÈš„情话åQŒéœ€è¦æ—¶åªè¦copy出来攑ֈ°QQ里面ž®Þp¡Œäº†ï¼Œ˜q™å°±æ˜¯æˆ‘的情话prototype了。(100块钱一份,你要不要åQ?

原始模型模式åQšé€šè¿‡¾l™å‡ºä¸€ä¸ªåŽŸåž‹å¯¹è±¡æ¥æŒ‡æ˜Žæ‰€è¦åˆ›å»ºçš„å¯¹è±¡çš„ç±»åž‹ï¼Œç„¶åŽç”¨å¤åˆ¶è¿™ä¸ªåŽŸåž‹å¯¹è±¡çš„æ–ÒŽ³•创徏出更多同¾cÕdž‹çš„对象。原始模型模式允许动态的增加或减ž®‘äñ”品类åQŒäñ”品类不需要非得有ä»ÖM½•事先¼‹®å®šçš„ç­‰¾U§ç»“构,原始模型模式适用于ä“Q何的½{‰çñ”¾l“构。缺ç‚ÒŽ˜¯æ¯ä¸€ä¸ªç±»éƒ½å¿…™å»é…å¤‡ä¸€ä¸ªå…‹éš†æ–¹æ³•ã€?

5、SINGLETON—俺æœ?个漂亮的老婆åQŒå¥¹ä»¬çš„老公都是我,我就是我们家里的老公SigletonåQŒå¥¹ä»¬åªè¦è¯´é““老公”,都是指的同一个ähåQŒé‚£ž®±æ˜¯æˆ?刚才做了个梦啦,哪有˜q™ä¹ˆå¥½çš„äº?

单例模式åQšå•ä¾‹æ¨¡å¼ç¡®ä¿æŸä¸€ä¸ªç±»åªæœ‰ä¸€ä¸ªå®žä¾‹ï¼Œè€Œä¸”è‡ªè¡Œå®žä¾‹åŒ–åÆˆå‘æ•´ä¸ªç³»¾lŸæä¾›è¿™ä¸ªå®žä¾‹å•例模式。单例模式只应在有真正的“单一实例”的需求时才可使用ã€?

¾l“构型模å¼?

6、ADAPTER—在朋友聚会上碰åˆîCº†ä¸€ä¸ªç¾Žå¥³SarahåQŒä»Žé¦™æ¸¯æ¥çš„åQŒå¯æˆ‘不会说¾_¤è¯­åQŒå¥¹ä¸ä¼šè¯´æ™®é€šè¯åQŒåªå¥½æ±‚助于我的朋友kent了,他作为我和Sarah之间的AdapteråQŒè®©æˆ‘å’ŒSarahå¯ä»¥ç›æ€º’交谈äº?也不知道他会不会耍我)

适配器(变压器)模式åQšæŠŠä¸€ä¸ªç±»çš„æŽ¥å£å˜æ¢æˆå®¢æˆ·ç«¯æ‰€æœŸå¾…çš„å¦ä¸€¿UæŽ¥å£ï¼Œä»Žè€Œä‹É原本因接口原因不匚w…è€Œæ— æ³•一起工作的两个¾c»èƒ½å¤Ÿä¸€èµ·å·¥ä½œã€‚适配¾cÕd¯ä»¥æ ¹æ®å‚æ•°è¿”˜q˜ä¸€ä¸ªåˆé€‚的实例¾l™å®¢æˆïL«¯ã€?

7、BRIDGE—早上碰到MMåQŒè¦è¯´æ—©ä¸Šå¥½åQŒæ™šä¸Šç¢°åˆ°MMåQŒè¦è¯´æ™šä¸Šå¥½åQ›ç¢°åˆ°MM½I¿äº†ä»¶æ–°è¡£æœåQŒè¦è¯´ä½ çš„衣服好漂亮哦,¼„°åˆ°MM新做的发型,要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”这¿Ué—®é¢˜ï¼Œè‡ªå·±ç”¨BRIDGE¾l„合一下不ž®Þp¡Œäº?

桥梁模式åQšå°†æŠ½è±¡åŒ–与实现化脱耦,使得二者可以独立的变化åQŒä¹Ÿž®±æ˜¯è¯´å°†ä»–们之间的强兌™”变成弱关联,也就是指在一个èÊYä»¶ç³»¾lŸçš„æŠ½è±¡åŒ–和实现化之间ä‹É用组å?聚合关系而不是ç‘ô承关¾p»ï¼Œä»Žè€Œä‹É两者可以独立的变化ã€?

8、COMPOSITE—Mary今天˜q‡ç”Ÿæ—¥ã€‚“我˜q‡ç”Ÿæ—¥ï¼Œä½ è¦é€æˆ‘一件礼物。”“嗯åQŒå¥½å§ï¼ŒåŽÕd•†åº—,你自己挑。”“这件T恤挺漂亮åQŒä¹°åQŒè¿™æ¡è£™å­å¥½çœ‹ï¼Œä¹ŽÍ¼Œ˜q™ä¸ªåŒ…也不错åQŒä¹°ã€‚”“喂åQŒä¹°äº†ä¸‰ä»¶äº†å‘€åQŒæˆ‘只答应送一件礼物的哦。”“什么呀åQŒT恤加裙子加包包,正好配成一套呀åQŒå°å§ï¼ŒéºÈƒ¦ä½ åŒ…èµäh¥ã€‚”“……”,MM都会用Composite模式了,你会了没有?

合成模式åQšåˆæˆæ¨¡å¼å°†å¯¹è±¡¾l„织到树¾l“构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树¾l“构表示出来。合成模式ä‹É得客æˆïL«¯æŠŠä¸€ä¸ªä¸ªå•独的成分对象和ç”׃»–们复合而成的合成对象同½{‰çœ‹å¾…ã€?

9、DECORATOR—Mary˜q‡å®Œè½®åˆ°Sarly˜q‡ç”Ÿæ—¥ï¼Œ˜q˜æ˜¯ä¸è¦å«å¥¹è‡ªå·±æŒ‘了åQŒä¸ç„¶è¿™ä¸ªæœˆä¼™é£Ÿè´¹è‚¯å®šçŽ©å®Œï¼Œæ‹¿å‡ºæˆ‘åŽ»òq´åœ¨åŽå±±™å¶ä¸Šç…§çš„照片åQŒåœ¨èƒŒé¢å†™ä¸Šâ€œæœ€å¥½çš„的礼物,ž®±æ˜¯çˆ×ƒ½ çš„Fita”,再到街上½C¼å“åº—买了个像框åQˆå–½C¼å“çš„MM也很漂亮哦)åQŒå†æ‰ùNš”壁搞¾ŸŽæœ¯è®¾è®¡çš„Mike设计了一个漂亮的盒子装è“v来……,我们都是DecoratoråQŒæœ€¾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发短信,手指都篏æ­ÖMº†åQŒæœ€˜q‘买了个新手机,可以把一些常用的句子存在手机里,要用的时候,直接拿出来,在前面加上MM的名字就可以发送了åQŒå†ä¸ç”¨ä¸€ä¸ªå­—一个字敲了。共享的句子ž®±æ˜¯FlyweightåQŒMM的名字就是提取出来的外部特征åQŒæ ¹æ®ä¸Šä¸‹æ–‡æƒ…况使用ã€?

享元模式åQšFLYWEIGHT在拳å‡ÀL¯”赛中指最轻量¾U§ã€‚äín元模式以å…׃ín的方式高效的支持大量的细¾_’度对象。äín元模式能做到å…׃ín的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部åQŒä¸ä¼šéšçŽ¯å¢ƒçš„æ”¹å˜è€Œæœ‰æ‰€ä¸åŒã€‚å¤–è•´çŠ¶æ€æ˜¯éšçŽ¯å¢ƒçš„æ”¹å˜è€Œæ”¹å˜çš„ã€‚å¤–è•´çŠ¶æ€ä¸èƒ½åª„å“å†…è•´çŠ¶æ€ï¼Œå®ƒä»¬æ˜¯ç›¸äº’ç‹¬ç«‹çš„ã€‚å°†å¯ä»¥å…׃ín的状态和不可以共享的状态从常规¾cÖM¸­åŒºåˆ†å¼€æ¥ï¼Œž®†ä¸å¯ä»¥å…׃ín的状态从¾c»é‡Œå‰”除出去。客æˆïL«¯ä¸å¯ä»¥ç›´æŽ¥åˆ›å»ø™¢«å…׃ín的对象,而应当ä‹Éç”¨ä¸€ä¸ªå·¥åŽ‚å¯¹è±¡è´Ÿè´£åˆ›å»ø™¢«å…׃ín的对象。äín元模式大òq…度的降低内存中对象的数量ã€?

12、PROXY—跟MM在网上聊天,一开头æ€ÀL˜¯â€œhi,你好â€?“你从哪儿来呀åQŸâ€â€œä½ å¤šå¤§äº†ï¼Ÿâ€â€œèín高多ž®‘å‘€åQŸâ€è¿™äº›è¯åQŒçœŸçƒ¦ähåQŒå†™ä¸ªç¨‹åºåšä¸ºæˆ‘çš„Proxy吧,凡是接收到这些话都设¾|®å¥½äº†è‡ªåŠ¨çš„å›žç­”åQŒæŽ¥æ”¶åˆ°å…¶ä»–的话时再通知我回½{”ï¼Œæ€Žä¹ˆæ øP¼Œé…·å§ã€?

代理模式åQšä»£ç†æ¨¡å¼ç»™æŸä¸€ä¸ªå¯¹è±¡æä¾›ä¸€ä¸ªä»£ç†å¯¹è±¡ï¼Œòq¶ç”±ä»£ç†å¯¹è±¡æŽ§åˆ¶å¯ÒŽºå¯¹è±¡çš„引用。代理就是一个äh或一个机构代表另一个äh或者一个机构采取行动。某些情况下åQŒå®¢æˆ·ä¸æƒÏxˆ–者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客æˆïL«¯åˆ†èöLä¸å‡ºä»£ç†ä¸»é¢˜å¯¹è±¡ä¸ŽçœŸå®žä¸»é¢˜å¯¹è±¡ã€‚ä»£ç†æ¨¡å¼å¯ä»¥åÆˆä¸çŸ¥é“çœŸæ­£çš„è¢«ä»£ç†å¯¹è±¡ï¼Œè€Œä»…ä»…æŒæœ‰ä¸€ä¸ªè¢«ä»£ç†å¯¹è±¡çš„æŽ¥å£ï¼Œ˜q™æ—¶å€™ä»£ç†å¯¹è±¡ä¸èƒ½å¤Ÿåˆ›å¾è¢«ä»£ç†å¯¹è±¡ï¼Œè¢«ä»£ç†å¯¹è±¡å¿…™åÀLœ‰¾pȝ»Ÿçš„å…¶ä»–è§’è‰²ä»£ä¸ºåˆ›å»ºåÆˆä¼ å…¥ã€?

è¡ŒäØ“æ¨¡å¼

13、CHAIN OF RESPONSIBLEITY—晚上去上英语课åQŒäؓ了好开溜坐åˆîCº†æœ€åŽä¸€æŽ’,哇,前面坐了好几个漂亮的MM哎,扑ּ ¾U¸æ¡åQŒå†™ä¸Šâ€œHi,可以做我的女朋友吗?如果不愿意请向前传”,¾U¸æ¡ž®×ƒ¸€ä¸ªæŽ¥ä¸€ä¸ªçš„传上åŽÖMº†åQŒç³Ÿ¾p•,传到½W¬ä¸€æŽ’çš„MM把纸条传¾l™è€å¸ˆäº†ï¼Œå¬è¯´æ˜¯ä¸ªè€å¤„奛_‘€åQŒå¿«è·?

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

èµäh¥å½¢æˆä¸€æ¡é“¾ã€‚请求在˜q™ä¸ªé“¾ä¸Šä¼ é€’,直到链上的某一个对象决定处理此è¯äh±‚ã€‚å®¢æˆ·åÆˆä¸çŸ¥é“é“¾ä¸Šçš„å“ªä¸€ä¸ªå¯¹è±¡æœ€¾lˆå¤„理这个请求,¾pȝ»Ÿå¯ä»¥åœ¨ä¸å½±å“å®¢æˆ·ç«¯çš„æƒ…况下动态的重新¾l„织铑֒Œåˆ†é…è´£ä“Q。处理者有两个选择åQšæ‰¿æ‹…è´£ä»ÀLˆ–者把责ä“Q推给下家。一个请求可以最¾lˆä¸è¢«ä“Q何接收端对象所接受ã€?
14、COMMAND—俺有一个MM安™‡Œ½Ž¡å¾—特别严,没法见面åQŒåªå¥½å€ŸåŠ©äºŽå¥¹å¼Ÿå¼Ÿåœ¨æˆ‘ä»¬ä¿©ä¹‹é—´ä¼ é€ä¿¡æ¯ï¼Œå¥¹å¯¹æˆ‘æœ‰ä»€ä¹ˆæŒ‡½Cºï¼Œž®±å†™ä¸€å¼ çº¸æ¡è®©å¥¹å¼Ÿå¼Ÿå¸¦¾l™æˆ‘。这不,她弟弟又传送过来一个COMMANDåQŒäؓ了感谢他åQŒæˆ‘请他吃了¼„—杂酱面åQŒå“ªçŸ¥é“他说åQšâ€œæˆ‘同时¾l™æˆ‘姐姐三个ç”ähœ‹å‹é€COMMANDåQŒå°±æ•îC½ æœ€ž®æ°”åQŒæ‰è¯ähˆ‘吃面。”,:-(

命ä×o模式åQšå‘½ä»¤æ¨¡å¼æŠŠä¸€ä¸ªè¯·æ±‚或者操作封装到一个对象中。命令模式把发出命ä×o的责ä»Õd’Œæ‰§è¡Œå‘½ä×o的责ä»Õdˆ†å‰²å¼€åQŒå§”‹z„¡»™ä¸åŒçš„对象。命令模式允许请求的一方和发送的一方独立开来,使得è¯äh±‚的一方不必知道接收请求的一方的接口åQŒæ›´ä¸å¿…知道è¯äh±‚是怎么被接æ”Óž¼Œä»¥åŠæ“ä½œæ˜¯å¦æ‰§è¡ŒåQŒä½•时被执行以及是怎么被执行的。系¾lŸæ”¯æŒå‘½ä»¤çš„æ’¤æ¶ˆã€?

15、INTERPRETER—俺有一个《æˆöMM真经》,上面有各¿UæˆöMM的攻略,比如说去吃西˜¡çš„æ­¥éª¤ã€åŽ»çœ‹ç”µå½Þqš„æ–ÒŽ³•½{‰ç­‰åQŒè·ŸMM¾U¦ä¼šæ—Óž¼Œåªè¦åšä¸€ä¸ªInterpreteråQŒç…§ç€ä¸Šé¢çš„脚本执行就可以了ã€?

解释器模式:¾l™å®šä¸€ä¸ªè¯­­a€åŽï¼Œè§£é‡Šå™¨æ¨¡å¼å¯ä»¥å®šä¹‰å‡ºå…¶æ–‡æ³•的一¿Uè¡¨½Cºï¼Œòq¶åŒæ—¶æä¾›ä¸€ä¸ªè§£é‡Šå™¨ã€‚客æˆïL«¯å¯ä»¥ä½¿ç”¨˜q™ä¸ªè§£é‡Šå™¨æ¥è§£é‡Š˜q™ä¸ªè¯­è¨€ä¸­çš„句子。解释器模式ž®†æ˜q°æ€Žæ ·åœ¨æœ‰äº†ä¸€ä¸ªç®€å•的文法后,使用模式设计解释˜q™äº›è¯­å¥ã€‚在解释器模式里面提到的语言是指ä»ÖM½•解释器对象能够解释的ä»ÖM½•¾l„合。在解释器模式中需要定义一个代表文法的命ä×o¾cȝš„½{‰çñ”¾l“æž„åQŒä¹Ÿž®±æ˜¯ä¸€¾pÕdˆ—的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的½{‰çñ”¾l“构中的对象的ä“Q何排列组合都是一个语­a€ã€?

 

16、ITERATOR—我çˆ×ƒ¸Šäº†MaryåQŒä¸™å¾ä¸€åˆ‡çš„向她求婚ã€?

MaryåQšâ€œæƒ³è¦æˆ‘è·Ÿä½ ¾l“婚åQŒå¾—½{”应我的条äšgâ€?

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

MaryåQšâ€œæˆ‘看上了那个一克拉的钻石â€?

我:“我乎ͼŒæˆ‘ä¹°åQŒè¿˜æœ‰å—åQŸâ€?

MaryåQšâ€œæˆ‘看上了湖边的那栋别墅â€?

我:“我乎ͼŒæˆ‘ä¹°åQŒè¿˜æœ‰å—åQŸâ€?

MaryåQšâ€œä½ çš„小弟弟必须要有50cm镎ì€?

我脑袋嗡的一壎ͼŒååœ¨æ¤…子上,一咬牙åQšâ€œæˆ‘剪,我剪åQŒè¿˜æœ‰å—åQŸâ€?

…�

˜q­ä»£å­æ¨¡å¼ï¼š˜q­ä»£å­æ¨¡å¼å¯ä»¥é¡ºåºè®¿é—®ä¸€ä¸ªèšé›†ä¸­çš„元素而不必暴露聚集的内部表象。多个对象聚在一起åŞ成的æ€ÖM½“¿UîC¹‹ä¸ø™šé›†ï¼Œèšé›†å¯¹è±¡æ˜¯èƒ½å¤ŸåŒ…容一¾l„对象的容器对象。è„P代子模式ž®†è„P代逻辑ž®è£…åˆîC¸€ä¸ªç‹¬ç«‹çš„子对象中åQŒä»Žè€Œä¸Žèšé›†æœ¬èín隔开。è„P代子模式½Ž€åŒ–了聚集的界面。每一个聚集对象都可以有一个或一个以上的˜q­ä»£å­å¯¹è±¡ï¼Œæ¯ä¸€ä¸ªè„P代子的è„P代状态可以是彼此独立的。è„P代算法可以独立于聚集角色变化ã€?

17、MEDIATOR—四个MM打麻ž®†ï¼Œç›æ€º’之间谁应该给谁多ž®‘é’±½Ž—不清楚了,òq怺å½“时我在旁边åQŒæŒ‰ç…§å„自的½{¹ç æ•°ç®—钱,赚了é’Þqš„从我˜q™é‡Œæ‹¿ï¼Œèµ”了é’Þqš„也付¾l™æˆ‘åQŒä¸€åˆ‡å°±OK啦,俺得åˆîCº†å››ä¸ªMM的电话ã€?

调停者模式:调停者模式包装了一¾pÕdˆ—å¯¹è±¡ç›æ€º’作用的方式,使得˜q™äº›å¯¹è±¡ä¸å¿…ç›æ€º’明显作用。从而ä‹É他们可以松散偶合。当某些对象之间的作用发生改变时åQŒä¸ä¼šç«‹å›_ª„å“å…¶ä»–çš„ä¸€äº›å¯¹è±¡ä¹‹é—´çš„ä½œç”¨ã€‚ä¿è¯è¿™äº›ä½œç”¨å¯ä»¥å½¼æ­¤ç‹¬ç«‹çš„å˜åŒ–ã€‚è°ƒåœè€…æ¨¡å¼å°†å¤šå¯¹å¤šçš„ç›æ€º’作用转化ä¸ÞZ¸€å¯¹å¤šçš„相互作用。调停者模式将对象的行为和协作抽象化,把对象在ž®å°ºåº¦çš„è¡ŒäØ“ä¸Šä¸Žå…¶ä»–å¯¹è±¡çš„ç›¸äº’ä½œç”¨åˆ†å¼€å¤„ç†ã€?

18、MEMENTO—同时跟几个MM聊天æ—Óž¼Œä¸€å®šè¦è®°æ¸…楚刚才跟MM说了些什么话åQŒä¸ç„¶MM发现了会不高兴的哦,òq怺æˆ‘有个备忘录åQŒåˆšæ‰ä¸Žå“ªä¸ªMM说了什么话我都拯‚´ä¸€ä»½æ”¾åˆ°å¤‡å¿˜å½•里面保存åQŒè¿™æ ·å¯ä»¥éšæ—¶å¯Ÿçœ‹ä»¥å‰çš„记录啦ã€?

备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏ž®è£…的条件下åQŒå°†ä¸€ä¸ªå¯¹è±¡çš„状态捉住,òq¶å¤–部化åQŒå­˜å‚¨è“v来,从而可以在ž®†æ¥åˆé€‚的时候把˜q™ä¸ªå¯¹è±¡˜q˜åŽŸåˆ°å­˜å‚¨è“v来的状态ã€?

19、OBSERVER—想知道å’׃»¬å…¬å¸æœ€æ–°MM情报吗?加入公司的MM情报邮äšg¾l„就行了åQŒtom负责搜集情报åQŒä»–发现的新情报不用一个一个通知我们åQŒç›´æŽ¥å‘布给邮äšg¾l„ï¼Œæˆ‘ä»¬ä½œäØ“è®¢é˜…è€…ï¼ˆè§‚å¯Ÿè€…ï¼‰ž®±å¯ä»¥åŠæ—¶æ”¶åˆ°æƒ…报啦

观察者模式:观察者模式定义了一¿Uä¸€é˜Ÿå¤šçš„依赖关¾p»ï¼Œè®©å¤šä¸ªè§‚察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化æ—Óž¼Œä¼šé€šçŸ¥æ‰€æœ‰è§‚察者对象,使他们能够自动更新自己ã€?

20、STATE—跟MM交往æ—Óž¼Œä¸€å®šè¦æ³¨æ„å¥¹çš„状态哦åQŒåœ¨ä¸åŒçš„çŠ¶æ€æ—¶å¥¹çš„è¡ŒäØ“ä¼šæœ‰ä¸åŒåQŒæ¯”如你¾U¦å¥¹ä»Šå¤©æ™šä¸ŠåŽÈœ‹ç”µåª„åQŒå¯¹ä½ æ²¡å…´è¶£çš„MMž®×ƒ¼šè¯´â€œæœ‰äº‹æƒ…啦”,对你不讨厌但˜q˜æ²¡å–œæ¬¢ä¸Šçš„MMž®×ƒ¼šè¯´â€œå¥½å•Šï¼Œä¸è¿‡å¯ä»¥å¸¦ä¸Šæˆ‘同事么åQŸâ€ï¼Œå·²ç»å–œæ¬¢ä¸Šä½ çš„MMž®×ƒ¼šè¯´â€œå‡ ç‚šw’ŸåQŸçœ‹å®Œç”µå½±å†åŽÀLˆöå§æ€Žä¹ˆæ øP¼Ÿâ€ï¼Œå½“然你看电媄˜q‡ç¨‹ä¸­è¡¨çŽ°è‰¯å¥½çš„è¯ï¼Œä¹Ÿå¯ä»¥æŠŠMM的状态从不讨厌不喜欢变成喜欢哦ã€?

çŠ¶æ€æ¨¡å¼ï¼šçŠ¶æ€æ¨¡å¼å…è®æ€¸€ä¸ªå¯¹è±¡åœ¨å…¶å†…部状态改变的时候改变行为。这个对象看上去象是改变了它的类一栗÷€‚çŠ¶æ€æ¨¡å¼æŠŠæ‰€ç ”ç©¶çš„å¯¹è±¡çš„è¡ŒäØ“åŒ…è£…åœ¨ä¸åŒçš„çŠ¶æ€å¯¹è±¡é‡ŒåQŒæ¯ä¸€ä¸ªçŠ¶æ€å¯¹è±¡éƒ½å±žäºŽä¸€ä¸ªæŠ½è±¡çŠ¶æ€ç±»çš„ä¸€ä¸ªå­¾c…R€‚状态模式的意图是让一个对象在其内部状态改变的时候,其行ä¸ÞZ¹Ÿéšä¹‹æ”¹å˜ã€‚状态模式需要对每一个系¾lŸå¯èƒ½å–得的状态创立一个状态类的子¾c…R€‚当¾pȝ»Ÿçš„状态变化时åQŒç³»¾lŸä¾¿æ”¹å˜æ‰€é€‰çš„子类ã€?/p>

   21、STRATEGY—跟不同¾cÕdž‹çš„MM¾U¦ä¼šåQŒè¦ç”¨ä¸åŒçš„½{–ç•¥åQŒæœ‰çš„请电媄比较好,有的则去吃小吃效果不错,有的åŽÀL“vè¾Ò޵ªæ¼«æœ€åˆé€‚ï¼Œå•ç›®çš„éƒ½æ˜¯äØ“äº†å¾—åˆ°MM的芳心,我的˜q½MM锦囊中有好多Strategy哦ã€?

½{–略模式åQšç­–略模式针对一¾l„算法,ž®†æ¯ä¸€ä¸ªç®—法封装到å…ähœ‰å…±åŒæŽ¥å£çš„独立的¾cÖM¸­åQŒä»Žè€Œä‹É得它们可以相互替换。策略模式ä‹Éå¾—ç®—æ³•å¯ä»¥åœ¨ä¸åª„å“åˆ°å®¢æˆ·ç«¯çš„æƒ…å†µä¸‹å‘ç”Ÿå˜åŒ–ã€‚ç­–ç•¥æ¨¡å¼æŠŠè¡ŒäØ“å’ŒçŽ¯å¢ƒåˆ†å¼€ã€‚çŽ¯å¢ƒç±»è´Ÿè´£¾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â€”æƒ…äºø™Š‚åˆîCº†åQŒè¦¾l™æ¯ä¸ªMM送一束鲜花和一张卡片,可是每个MM送的花都要针对她个äh的特点,每张卡片也要æ ÒŽ®ä¸ªäh的特ç‚ÒŽ¥æŒ‘,我一个äh哪搞得清楚,˜q˜æ˜¯æ‰¾èŠ±åº—è€æ¿å’Œç¤¼å“åº—è€æ¿åšä¸€ä¸‹VisitoråQŒè®©èŠ±åº—è€æ¿æ ÒŽ®MM的特炚w€‰ä¸€æŸèбåQŒè®©½C¼å“åº—老板也根据每个äh特点选一张卡åQŒè¿™æ ·å°±è½ÀL¾å¤šäº†åQ?

讉K—®è€…模式:讉K—®è€…模式的目的是封装一些施加于某种数据¾l“构元素之上的操作。一旦这些操作需要修改的话,接受˜q™ä¸ªæ“ä½œçš„æ•°æ®ç»“构可以保持不变。访问者模式适用于数据结构相å¯ÒŽœªå®šçš„¾pȝ»ŸåQŒå®ƒæŠŠæ•°æ®ç»“构和作用于结构上的操作之间的耦合解脱开åQŒä‹É得操作集合可以相对自ç”Þqš„æ¼”化。访问者模式ä‹É得增加新的操作变的很å®ÒŽ˜“åQŒå°±æ˜¯å¢žåŠ ä¸€ä¸ªæ–°çš„è®¿é—®è€…ç±»ã€‚è®¿é—®è€…æ¨¡å¼å°†æœ‰å…³çš„è¡Œä¸ºé›†ä¸­åˆ°ä¸€ä¸ªè®¿é—®è€…å¯¹è±¡ä¸­åQŒè€Œä¸æ˜¯åˆ†æ•£åˆ°ä¸€ä¸ªä¸ªçš„节点类中。当使用讉K—®è€…模式时åQŒè¦ž®†å°½å¯èƒ½å¤šçš„对象‹¹è§ˆé€»è¾‘攑֜¨è®‰K—®è€…类中,而不是放到它的子¾cÖM¸­ã€‚访问者模式可以跨˜q‡å‡ ä¸ªç±»çš„ç­‰¾U§ç»“构访问属于不同的½{‰çñ”¾l“构的成员类ã€?/p>

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

 



]]>
Object Hierarchy and Inheritance in JavaScripthttp://www.aygfsteel.com/mkchen/archive/2007/01/21/95144.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sun, 21 Jan 2007 08:19:00 GMThttp://www.aygfsteel.com/mkchen/archive/2007/01/21/95144.htmlhttp://www.aygfsteel.com/mkchen/comments/95144.htmlhttp://www.aygfsteel.com/mkchen/archive/2007/01/21/95144.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/95144.htmlhttp://www.aygfsteel.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://www.aygfsteel.com/mkchen/archive/2007/01/21/95139.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sun, 21 Jan 2007 07:49:00 GMThttp://www.aygfsteel.com/mkchen/archive/2007/01/21/95139.htmlhttp://www.aygfsteel.com/mkchen/comments/95139.htmlhttp://www.aygfsteel.com/mkchen/archive/2007/01/21/95139.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/95139.htmlhttp://www.aygfsteel.com/mkchen/services/trackbacks/95139.html

    跨越边界: JavaScript 语言ç‰ÒŽ€?/h1>

    研究¾~–程语言中的“丑ž®é¸­â€?/p> developerWorks
    文档选项

    未显½Cºéœ€è¦?JavaScript 的文档选项

    ž®†æ­¤™åµä½œä¸ºç”µå­é‚®ä»¶å‘é€? /></td><td width=

    ž®†æ­¤™åµä½œä¸ºç”µå­é‚®ä»¶å‘é€?/b>

    ž®†æ­¤™åµä½œä¸ºç”µå­é‚®ä»¶å‘é€? src=

    ž®†æ­¤™åµä½œä¸ºç”µå­é‚®ä»¶å‘é€?/font>

    样例代码


    拓展 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 ¾|‘页更加˜q·äh。而完整的 Web 开发框æžÓž¼Œæ¯”如 Apache CocoonåQŒåˆ™è®?JavaScript 的应用越来越多,使其不只限于是一¿Uç”¨äºŽåˆ¶ä½?Web ™åµé¢çš„简单脚本。JavaScript 的一¿Uç§°ä¸?ActionScript 的派生物也推动了 Macromedia çš?Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino è®?JavaScript æˆäØ“äº?Javaâ„?开发äh员所首选的一¾c»è„šæœ¬è¯­­a€åQˆå‚è§?参考资æ–?/font>åQ‰ã€?

    我的好友兼同äº?Stuart Halloway æ˜?Ajax æ–šw¢çš„专å®Óž¼Œæ›‘Öœ¨å…¶æ•™æŽˆçš„ JavaScript 评¡¨‹ä¸­åš˜q‡è¿™æ ïLš„开场白åQšâ€œåˆ° 2011 òqß_¼ŒJavaScript ž®†è¢«å…¬è®¤ä¸ºæ˜¯ä¸€¿Uæ‹¥æœ‰å¼€å‘现代应用程序所需的一整套新特性的语言â€?。他¾l§è€Œä»‹¾lè¯´ JavaScript ½E‹åºè¦æ¯”¾cÖM¼¼çš?Java ½E‹åºç´§å¯†åå€ï¼Œòq¶ç‘ô¾l­å±•½CÞZº†ä½¿å…¶ä¹‹æ‰€ä»¥å¦‚此的一些语­a€ç‰ÒŽ€§ã€?

    关于˜q™ä¸ª¾pÕdˆ—

    åœ?跨越边界¾pÕdˆ—ä¸?/font>åQŒä½œè€?Bruce Tate 提出了这样一个主张:今天çš?Java ½E‹åºå‘˜é€šè¿‡å­¦ä¹ å…¶ä»–技术和语言åQŒä¼šå¾—到很好的帮助。编½E‹é¢†åŸŸå·²¾lå‘生了变化åQŒJava 技术不再是所有开发项目理所当然的最佳选择。其他框架正在媄å“?Java 框架构徏的方式,而从其他语言学到的概念也有助äº?Java ¾~–程。对 PythonåQˆæˆ– Ruby、Smalltalk ½{‰ç­‰åQ‰ä»£ç çš„¾~–写可能改变 Java ¾~–码的方式ã€?/p>

    ˜q™ä¸ª¾pÕdˆ—介绍的编½E‹æ¦‚念和技术,ä¸?Java 开发有æ ÒŽœ¬çš„不同,但可以直接应用于 Java ¾~–程。在某些情况下,需要集成这些技术来利用它们。在其他情况下,可以直接应用˜q™äº›æ¦‚念。单独的工具òq¶ä¸é‡è¦åQŒé‡è¦çš„æ˜¯å…¶ä»–语­a€å’Œæ¡†æž¶å¯ä»¥åª„å“?Java ½C‘ÖŒºä¸­çš„开发äh员、框æžÓž¼Œç”šè‡³æ˜¯åŸºæœ¬æ–¹å¼ã€?

    在这½‹‡æ–‡ç« ä¸­åQŒæˆ‘ž®†å¸¦æ‚¨æŽ¢½I?JavaScript 的一些特性,看看˜q™äº›ç‰ÒŽ€§å¦‚何让它如此具有吸引力åQ?

    • 高阶函数åQ?/b> ä¸€ä¸ªé«˜é˜¶å‡½æ•°å¯ä»¥å°†å‡½æ•°ä½œäØ“å‚æ•°åQŒä¹Ÿå¯ä»¥˜q”回一个函数。此ç‰ÒŽ€§è®© JavaScript ½E‹åºå‘˜å¯ä»¥ç”¨ Java 语言所不能提供的方法来操纵函数ã€?br />
    • 动态类型:通过延迟¾l‘定åQŒJavaScript 可以更准¼‹®å’Œæ›´çµ‹z…R€?br />
    • 灉|´»çš„对象模型:JavaScript 的对象模型ä‹É用一¿Uç›¸å¯¹ä¸å¸¸è§çš„æ–¹å¼è¿›è¡Œç‘ôæ‰?—â€?¿UîCؓ原型 —â€?而不æ˜?Java 语言中更常见的基于类的对象模型ã€?

    您可能已¾lç†Ÿæ‚‰åŠ¨æ€ç±»åž‹æ¨¡åž‹ã€é«˜é˜¶å‡½æ•°åŞ式的函数式编½E‹ä»¥åŠå¼€æ”‘Ö¯¹è±¡æ¨¡åž‹è¿™äº›æ¦‚å¿µï¼Œå› äØ“æˆ‘åœ¨å…¶ä»–çš?i>跨越边界 ¾pÕdˆ—文章中已¾lä½œ˜q‡ç›¸å…³çš„介绍。如果您从未˜q›è¡Œ˜q‡ä“Q何正式的 JavaScript å¼€å‘ï¼Œæ‚¨å¾ˆå¯èƒ½ä¼šè®¤ä¸ø™¿™äº›ç‰¹æ€§å±žäºŽéžå¸¸å¤æ‚的语言åQŒä¾‹å¦?Python、Lisp、Smalltalk å’?HaskellåQŒè€Œç»éžåƒ JavaScript ˜q™æ ·çš„语­a€æ‰€èƒ½æä¾›çš„。因此,我将用实际的代码½CÞZ¾‹æ¥è¯´æ˜Žè¿™äº›æ¦‚å¿üc€?

    立即开�/span>

    您无需讄¡½® JavaScript。如果您可以在浏览器中阅è¯ÀL­¤½‹‡æ–‡ç« ï¼Œž®Þp¯æ˜Žæ‚¨å·²ç»å‡†å¤‡ž®ÞqÈA了。本文包含的所有编½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Œåƈ在浏览器中加载此文äšgåQˆå‚çœ?下蝲 部分以获得本文ä‹É用的所有示ä¾?HTML æ–‡äšgåQ‰ã€‚注意到每次重蝲此页面时åQŒè¯¥ä»£ç éƒ½ä¼šç«‹å³æ‰§è¡Œã€?/p>

    alert 是个函数调用åQŒåªæœ‰ä¸€ä¸ªå­—½W¦ä¸²ä½œäؓ参数。图 1 昄¡¤ºäº†ç”±æ¸…单 1 中的代码弹出的警告框åQŒæ˜¾½Cºæ–‡æœ?“Hello, World”。如果代码在 HTML body 之内åQˆç›®å‰åƈ未指定ä“Qä½?bodyåQŒä½†‹¹è§ˆå™¨èƒ½æŽ¥å—不规则的 HTMLåQŒåÆˆä¸”æ•´ä¸ªé¡µé¢éƒ½é»˜ç„¶ä½œäØ“ä¸€ä¸?body 被处理)。页面一旦加载,JavaScript ž®×ƒ¼šç«‹å³æ‰§è¡Œã€?



    å›?1. Hello, world
    Hello, World.

    如果要åšg˜qŸæ‰§è¡Œï¼Œå¯ä»¥åœ?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 æ–‡äšgåQŒåœ¨‹¹è§ˆå™¨å†…加蝲该文ä»Óž¼Œå•击 Say Hello 按钮åQŒç»“果如å›?2 所½Cºï¼š



    �2. 延迟执行
    延迟执行




    回页�/font>


    高阶函数

    ä»?清单 2åQŒå¯ä»¥å¤§è‡´ä½“会到一äº?JavaScript 在操¾Uµå‡½æ•°æ–¹é¢çš„能力。将函数名称传递给 HTML button 标记òq¶åˆ©ç”?HTML 的内¾|®äº‹ä»¶æ¨¡åž‹ã€‚ä‹Éç”?JavaScript æ—Óž¼Œæˆ‘会¾lå¸¸åœ¨å˜é‡æˆ–数组中存储函敎ͼˆåœ¨æœ¬æ–‡åŽé¢çš„ 对象模型 一节,您会看到 JavaScript 对象模型½{–略大量使用了此技巧)。例如,查看一下清å?3åQ?



    清单 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 中的一¾cÕd¯¹è±¡ï¼Œå¯ä»¥è‡ªç”±åœ°æ“¾Uµå®ƒä»¬ã€‚首先我声明两个函数åQ?code>hot å’?coldã€‚åÆˆåˆ†åˆ«åœ¨ä¸åŒçš„å˜é‡å­˜å‚¨å®ƒä»¬ã€‚å•å‡?Hot æˆ?Cold 按钮会调用对应的函数åQŒç”Ÿæˆä¸€ä¸ªå‘Šè­¦ã€‚接下来åQŒå£°æ˜Žå¦ä¸€ä¸ªå‡½æ•°ç”¨æ¥äº¤æ?Hot å’?Cold 按钮的å€û|¼Œž®†æ­¤å‡½æ•°ä¸Žç¬¬ä¸‰ä¸ªæŒ‰é’®å…Œ™”åQŒè¯¥æŒ‰é’®æ˜„¡¤ºå¦‚图 3 所½Cºçš„告警åQ?



    �3. 操纵函数

    ˜q™ä¸ªä¾‹å­è¯´æ˜Žå¯ä»¥åƒå¤„理其他变量一样处理函数。C 开发äh员很å®ÒŽ˜“ž®†æ­¤æ¦‚念看作æ˜?i>函数指针 功能åQŒä½† JavaScript çš„é«˜é˜¶å‡½æ•°çš„åŠŸèƒ½æ›´äØ“å¼ºå¤§ã€‚è¯¥ç‰ÒŽ€§è®© JavaScript ½E‹åºå‘˜èƒ½å¤Ÿåƒå¤„理其他变量¾cÕdž‹ä¸€æ ¯‚½»æ‘Ö¤„理动作或函数ã€?/p>

    ž®†å‡½æ•°ç”¨ä½œå‡½æ•°çš„参数åQŒæˆ–ž®†å‡½æ•îC½œä¸ºå€ÆD¿”回,˜q™äº›æ¦‚念属于高阶函数的领域。清å?4 å¯?清单 3 做了一点点修改åQŒæ˜¾½CÞZº†èƒ½è¿”回函数的高阶函数å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™ä¸ªä¾‹å­è§£å†³äº†ä¸€ä¸ªå¸¸è§é—®é¢˜ï¼šå¦‚何ž®†æ›´æ”¹ä¸­çš„行为附加到用户接口事äšgåQŸé€šè¿‡é«˜é˜¶å‡½æ•°åQŒè¿™å¾ˆå®¹æ˜“做到ã€?code>temperature 高阶函数˜q”回 current çš„å€û|¼Œè€?current 又可以有 hot æˆ?cold 函数。看一下这个有些陈旧的函数调用åQ?code>temperature()()。第一¾l„括åïL”¨äºŽè°ƒç”?temperature 函数。第二组括号调用ç”?temperature˜q”回 的函数。图 4 昄¡¤ºäº†è¾“出:



    �4. 高阶函数
    高阶函数

    高阶函数是函数式¾~–程的基¼‹€åQŒå¯¹æ¯”面向对象编½E‹ï¼Œå‡½æ•°å¼ç¼–½E‹ä»£è¡¨äº†æ›´é«˜¾U§åˆ«çš„æŠ½è±¡ã€‚但 JavaScript çš„å®žåŠ›åÆˆä¸ä»…é™äºŽé«˜é˜¶å‡½æ•°ã€‚JavaScript çš„åŠ¨æ€ç±»åž‹å°±æžäØ“é€‚åˆ UI 开发ã€?/p>



    回页�/font>


    动态类�/span>

    通过静态类型,¾~–译器可以检查参数和变量的值或针对一个给定操作所允许的返回倹{€‚其优势是编译器可以做额外的错误‹‚€æŸ¥ã€‚è€Œä¸”é™æ€ç±»åž‹è¿˜å¯ä»¥ä¸ø™¯¸å¦?IDE ˜q™æ ·çš„å·¥å…ähä¾›æ›´å¤šä¿¡æ¯ï¼Œå¸¦æ¥å…¶ä»–一些特性,比如更好的代码完成功能。但静态类型也存在着如下一些劣势:

    • 必须提前声明意图åQŒè¿™å¸¸å¸¸ä¼šå¯¼è‡´çµ‹zÀL€§é™ä½Žã€‚例如,更改一ä¸?Java ¾cÕd°±ä¼šæ›´æ”¹ç±»çš„类型,因而必™å»é‡æ–°ç¼–译。对比之下,Ruby 允许开攄¡š„¾c»ï¼Œä½†æ›´æ”¹ä¸€ä¸?Java ¾c»è¿˜æ˜¯ä¼šæ›´æ”¹¾cȝš„¾cÕdž‹ã€?br />
    • 要实现相同的功能åQŒå¿…™å»è¾“入更多的代码。例如,必须用参数åŞ式包括进¾cÕdž‹ä¿¡æ¯åQŒå¿…™åȝ”¨å‡½æ•°å½¢å¼˜q”回值和所有变量的¾cÕdž‹ã€‚另外,˜q˜å¿…™åÕd£°æ˜Žæ‰€æœ‰å˜é‡åƈ昑ּåœ°è{化类型ã€?br />
    • 静态语­a€çš„ç¼–è¯?部çÖv周期要比动态语­a€çš„部¾|²å‘¨æœŸé•¿åQŒå°½½Ž¡ä¸€äº›å·¥å…·å¯è¢«ç”¨æ¥åœ¨æŸç§½E‹åº¦ä¸Šç¼“解这一问题ã€?

    静态类型更适合用于构徏中间件或操作¾pȝ»Ÿçš„语­a€ä¸­ã€‚UI 开发常帔Rœ€è¦æ›´é«˜çš„æ•ˆçŽ‡å’Œçµ‹zÀL€§ï¼Œæ‰€ä»¥æ›´é€‚合采用动态类型。我æ·ÞqŸ¥˜q™ç§åšæ³•存在危险。相信ä‹É用过 JavaScript çš?Web 开发äh员都曄¡»ä¸ºç¼–译器本应‹‚€‹¹‹åˆ°çš„错误类型的变量而绞ž®½è„‘汁。但它所带来的优势同样不可否认。下面将举例加以说明ã€?/p>

    首先åQŒè€ƒè™‘一个对象的情况。在清单 5 中,创徏一个新对象åQŒåƈ讉K—®ä¸€ä¸ªä¸å­˜åœ¨çš„å±žæ€§ï¼ŒåäØ“ coloråQ?/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“合èµäh¥åQŒè¿˜å¯ä»¥å¼•å…¥è¡ŒäØ“ã€‚è®°ä½ï¼Œå˜é‡å¯ä»¥ä¿å­˜å‡½æ•°åQæ‰€ä»¥ï¼ŒåŸÞZºŽåŠ¨æ€ç±»åž‹å’Œé«˜é˜¶å‡½æ•°åQŒæ‚¨å¯ä»¥åœ¨ä“Q何时候向¾cÖM¸­å¼•å…¥ä»ÀL„çš„行为ã€?

    可以è½ÀL¾åœ°é‡å†?清单 5åQŒä‹É其如清单 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º†å¯ä»¥ä½œäؓ所有对象的模板的新¾c…R€‚然后调ç”?new 来实例化该模板,创徏一个新对象。而在 JavaScript 中,所创徏的是一个原型,此原型是一个实例,可以创徏所有未来的对象ã€?

    现在先暂且放下这些抽象的概念åQŒåŽ»æŸ¥çœ‹ä¸€äº›å®žé™…ä»£ç ã€‚æ¯”å¦‚ï¼Œæ¸…å• 7 创徏了一个简单的 AnimalåQŒå®ƒå…ä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ºŽåŽŸåž‹æˆ–çŽ°æœ‰çš„å¯¹è±¡çš„å®žä¾‹æ¥æž„é€ å¯¹è±¡ï¼Œè€ŒéžåŸÞZºŽ¾cÀL¨¡æÑ€?code>funct() 是一¿Uè°ƒç”¨ï¼Œä½?new Animal() 却基äº?Animal 内的原型构造一个对象。最后,åœ?JavaScript ä¸­ï¼Œå¯¹è±¡åªæ˜¯å‡½æ•°å’Œå˜é‡çš„é›†åˆã€‚æ¯ä¸ªå¯¹è±¡åÆˆä¸ä¸Ž¾cÕdž‹ç›¸å…³åQŒæ‰€ä»¥å¯ä»¥è‡ªç”±åœ°ä¿®æ”¹˜q™ç§¾l“æž„ã€?

    回到 清单 7。如您所见,JavaScript åŸÞZºŽåœ?Animal 中指定的原型定义一个新对象åQ?code>myAnimal。ç‘ô而可以ä‹É用原型中的属性和函数åQŒç”šæˆ–é‡å®šä¹‰å‡½æ•°å’Œå±žæ€§ã€‚è¿™¿Uçµ‹zÀL€§å¯èƒ½ä¼šè®?Java 开发äh员受不了åQŒå› ä¸ÞZ»–们不习惯˜q™ç§è¡ŒäØ“åQŒä½†å®ƒçš„¼‹®æ˜¯ä¸€¿Uååˆ†å¼ºå¤§çš„æ¨¡åž‹ã€?/p>

    现在我还要更深入一步。您˜q˜å¯ä»¥ä‹É用名ä¸?prototype 实例变量来指定对象的基础。方法是讄¡½® prototype 实例变量使其指向¾l§æ‰¿é“„¡š„父。如此设¾|?prototype 之后åQŒæ‚¨æ‰€åˆ›å¾çš„对象会为未指定的那些对象ç‘ô承属性和函数。这样一来,您就可以模仿面向对象的ç‘ô承概å¿üc€‚以清单 8 ä¸ÞZ¾‹åQ?



    清单 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> 原型中查找,依此¾cÀLލã€?

    那么åQŒJavaScript çš„ç‘ô承模型到底是什么样的?˜q™å–决于您如何对它进行定义。您需要定义ç‘ô承行ä¸ÞZ»¥ä¾¿å¯ä»¥è¦†ç›–它。然而,从本质上è®ÔŒ¼ŒJavaScript 更像是一¿Uå‡½æ•°å¼è¯­è¨€åQŒè€Œéžé¢å‘对象的语­a€åQŒå®ƒä½¿ç”¨ä¸€äº›æ™ºèƒ½çš„è¯­æ³•å’Œè¯­ä¹‰æ¥ä»¿çœŸé«˜åº¦å¤æ‚çš„è¡Œä¸ºã€‚å…¶å¯¹è±¡æ¨¡åž‹æžäØ“ç‰|´»ã€å¼€æ”‘Ö’Œå¼ºå¤§åQŒå…·æœ‰å…¨éƒ¨çš„反射性。有些äh可能会说它太˜q‡çµ‹z…R€‚而我的忠告则是,按具体作业的需要选择合适的工具ã€?/p>



    回页�/font>


    ¾l“束è¯?/span>

    JavaScript 对象模型构徏在该语言的其他功能之上来支持大量的库åQŒæ¯”å¦?DojoåQˆå‚è§?参考资æ–?/font>åQ‰ã€‚è¿™¿Uçµ‹zÀL€§è®©æ¯ä¸ªæ¡†æž¶èƒ½å¤Ÿä»¥ä¸€¿Uç²¾¾l†çš„æ–¹å¼æ›´æ”¹å¯¹è±¡æ¨¡åž‹ã€‚在某种½E‹åº¦ä¸Šï¼Œ˜q™ç§ç‰|´»æ€§æ˜¯ä¸€¿Uæžå¤§çš„¾~ºç‚¹ã€‚å®ƒå¯ä»¥å¯ÆD‡´å¯æ€•的互操作性问题(ž®½ç®¡è¯¥è¯­­a€çš„灵‹zÀL€§å¯ä»¥éƒ¨åˆ†ç¼“解这些问题)ã€?

    而另一斚w¢åQŒçµ‹zÀL€§åˆæ˜¯ä¸€¿Uå·¨å¤§çš„优势。Java 语言一直苦于无法充分增强其灉|´»æ€§ï¼ŒåŽŸå› æ˜¯å®ƒçš„åŸºæœ¬å¯¹è±¡æ¨¡åž‹è¿˜æœªçµ‹zÕdˆ°å¯ä»¥è¢«æ‰©å±•çš„½E‹åº¦ã€‚一个典型的企业¾U§å¼€å‘ähå‘˜äØ“èƒ½å¤ŸæˆåŠŸä½¿ç”¨ Java 语言必须要学习很多东西,而新出现的一些优¿U€çš„开放源码项目和新技术,比如面向斚w¢¾~–程、Spring ¾~–程框架和字节码增强库,则带来了大量要学的代码ã€?

    最后,JavaScript 优秀的灵‹zÀL€§çš„¼‹®è®©æ‚¨ä½“会到了一些高阶语­a€çš„强大功能。当然您无需选择为每个项目或大多数项目都做这æ ïLš„æƒè¡¡å’ŒæŠ˜è¡—÷€‚但了解一¿Uè¯­­a€çš„优势和劣势 —â€?通过参考大量信息,而不仅仅åŸÞZºŽòq¿å‘Šå®£ä¼ æˆ–公众意è§?—â€?会让您可以更好地控制何时需要ä‹É用以及何时不能ä‹É用这¿Uè¯­­a€ã€‚当您在修改 JavaScript Web ž®éƒ¨ä»¶æ—¶åQŒæ‚¨è‡›_°‘知道该如何让此语­a€å‘挥它最大的优势。请¾l§ç®‹è·¨è¶Šè¾¹ç•Œå§ã€?/p>

    参考资�

    学习
    • 您可以参阅本文在 developerWorks 全球站点上的 英文原文 ã€?br />
    • Java To Ruby: Things Every Manager Should Know åQˆPragmatic BookshelfåQ?006 òqß_¼‰åQšæœ¬æ–‡ä½œè€…æ‰€è‘—çš„ä¹¦ï¼Œä»‹ç»äº†ä½•æ—¶ä½•åœ°å¯ä»¥ä»Ž Java ¾~–程转换åˆ?Ruby on RailsåQŒä»¥åŠå¦‚何进行è{换ã€?

    • Beyond Java åQˆO'ReillyåQ?005 òqß_¼‰åQšæœ¬æ–‡ä½œè€…æ‰€è‘—çš„ä¹¦ï¼Œä»‹ç»äº?Java 的兴起和兴盛åQŒä»¥åŠèƒ½å¤Ÿåœ¨æŸäº›é¢†åŸŸæŒ‘战 Java òq›_°çš„æŠ€æœ¯ã€?

    • Scriptaculous å’?PrototypeåQšä¸¤¿U?JavaScript 框架åQŒé€šè¿‡ Ruby on Rails 助力 Ajaxã€?br />
    • Object Hierarchy and Inheritance in JavaScript åQšæœ‰å…?JavaScript ¾l§æ‰¿çš„很好资源ã€?

    • Ajaxian åQšè¿™ä¸?Ajax 的门æˆïL½‘站上有所有有å…?Ajax çš„æ°å‡ø™®¨è®ºï¼Œæžå¤§åœ°æŽ¨åŠ¨äº† JavaScript 的复苏ã€?

    • Dojo åQšä¸€ä¸?JavaScript 开放源码工å…ïL®±ã€?br />
    • Rhino åQšJVM 上的 JavaScript 引擎ã€?br />
    • 用函数式¾~–程技术编写优¾ŸŽçš„ JavaScript åQˆdeveloperWorksåQ?006 òq?7 月)åQšä½œè€…解释了如何使用 JavaScript(TM)™(JavaScript 能导入函数式¾~–程的构造和ç‰ÒŽ€§ï¼‰¾~–写优美的代码ã€?br />
    • Java 技术专åŒ?/font> åQšæ•°ç™„¡¯‡ Java ¾~–程各方面的文章ã€?br />
    • Ajax 技术资源中å¿?/font> åQšèŽ·å¾?developerWorks 上有å…?Ajax 的所有信息ã€?/li>


    ]]>[转]sqlserverä¸?sql¾~–程的几个小常识http://www.aygfsteel.com/mkchen/archive/2007/01/07/92212.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sun, 07 Jan 2007 06:34:00 GMThttp://www.aygfsteel.com/mkchen/archive/2007/01/07/92212.htmlhttp://www.aygfsteel.com/mkchen/comments/92212.htmlhttp://www.aygfsteel.com/mkchen/archive/2007/01/07/92212.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/92212.htmlhttp://www.aygfsteel.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://www.aygfsteel.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://www.aygfsteel.com/mkchen/archive/2006/12/27/90397.html</guid><wfw:comment>http://www.aygfsteel.com/mkchen/comments/90397.html</wfw:comment><comments>http://www.aygfsteel.com/mkchen/archive/2006/12/27/90397.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/mkchen/comments/commentRss/90397.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.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 投票æ€ÖMh‹Æ?3<br />关键å­? <!-- end of div title --><div id="wmqeeuq" class="summary"><div id="wmqeeuq" class="left"></div><div id="wmqeeuq" class="center"><h4>摘要:</h4>Acegi安全¾pȝ»ŸåQŒæ˜¯ä¸€ä¸ªç”¨äºŽSpring Framework的安全框æžÓž¼Œèƒ½å¤Ÿå’Œç›®å‰æµè¡Œçš„Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean ContextåQŒæ‹¦æˆªå™¨å’Œé¢å‘接口的¾~–程方式。因此,Acegi安全¾pȝ»Ÿèƒ½å¤Ÿè½ÀL¾åœ°é€‚用于复杂的安全需求ã€?</div><div id="wmqeeuq" class="right"><div id="wmqeeuq" 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="wmqeeuq" class="overflow" id="text">           Acegi安全¾pȝ»ŸåQŒæ˜¯ä¸€ä¸ªç”¨äºŽSpring Framework的安全框æžÓž¼Œèƒ½å¤Ÿå’Œç›®å‰æµè¡Œçš„Web容器无缝集成。它使用了Spring的方式提供了安全和认证安全服务,包括使用Bean ContextåQŒæ‹¦æˆªå™¨å’Œé¢å‘接口的¾~–程方式。因此,Acegi安全¾pȝ»Ÿèƒ½å¤Ÿè½ÀL¾åœ°é€‚用于复杂的安全需求ã€?br />       安全涉及åˆîC¸¤ä¸ªä¸åŒçš„æ¦‚念åQŒè®¤è¯å’ŒæŽˆæƒã€‚前者是关于¼‹®è®¤ç”¨æˆ·æ˜¯å¦¼‹®å®žæ˜¯ä»–们所宣称的èín份。授权则是关于确认用æˆäh˜¯å¦æœ‰å…è®¸æ‰§è¡Œä¸€ä¸ªç‰¹å®šçš„æ“ä½œã€?br />       在Acegi安全¾pȝ»Ÿä¸­ï¼Œéœ€è¦è¢«è®¤è¯çš„ç”¨æˆøP¼Œ¾pȝ»Ÿæˆ–代理称ä¸?Principal"。Acegi安全¾pȝ»Ÿå’Œå…¶ä»–的安全¾pȝ»Ÿä¸åŒåQŒå®ƒòq¶æ²¡æœ‰è§’色和用户¾l„的概念ã€?br />Acegi¾pȝ»Ÿè®¾è®¡<br />  关键¾l„äšg<br />      Acegi安全¾pȝ»ŸåŒ…含以下七个关键的功能组ä»Óž¼š<br />        1 Authentication对象åQŒåŒ…含了PrincipalåQŒCredentialå’ŒPrincipal的授权信息。同时还可以包含关于发è“v认证è¯äh±‚的客æˆïLš„其他信息åQŒå¦‚IP地址ã€?br />        2 ContextHolder对象åQŒä‹É用ThreadLocal储存Authentication对象的地斏V€?br />        3 AuthenticationManageråQŒç”¨äºŽè®¤è¯ContextHolder中的Authentication对象ã€?br />        4 AccessDecissionManageråQŒç”¨äºŽæŽˆæƒä¸€ä¸ªç‰¹å®šçš„æ“ä½œã€?br />        5 RunAsManageråQŒå½“执行特定的操作时åQŒç”¨äºŽé€‰æ‹©æ€§åœ°æ›¿æ¢Authentication对象ã€?br />        6 Secure Object拦截器,用于协调AuthenticationManageråQŒAccessDecissionManageråQŒRunAsManager和特定操作的执行ã€?br />        7 ObjectDefinitionSourceåQŒåŒ…含了特定操作的授权定义ã€?br />      ˜q™ä¸ƒä¸ªå…³é”®çš„功能¾l„äšg的关¾pÕd¦‚下图所½Cºï¼ˆå›¾ä¸­ç°è‰²éƒ¨åˆ†æ˜¯å…³é”®ç»„ä»Óž¼‰åQ?br /><br /><br /><b>安全½Ž¡ç†å¯¹è±¡</b><br />       Acegi安全¾pȝ»Ÿç›®å‰æ”¯æŒä¸¤ç±»å®‰å…¨½Ž¡ç†å¯¹è±¡ã€?br />       ½W¬ä¸€¾cȝš„安全½Ž¡ç†å¯¹è±¡½Ž¡ç†AOP Allianceçš„MethodInvocationåQŒå¼€å‘äh员可以用它来保护Springå®¹å™¨ä¸­çš„ä¸šåŠ¡å¯¹è±¡ã€‚äØ“äº†ä‹ÉSpring½Ž¡ç†çš„Beanå¯ä»¥ä½œäØ“MethodInvocation来ä‹É用,Bean可以通过ProxyFactoryBeanå’ŒBeanNameAutoProxyCreator来管理,ž®±åƒåœ¨Spring的事务管理一样ä‹É用ã€?br />       ½W¬äºŒ¾cÀL˜¯FilterInvocation。它用过滤器åQˆFilteråQ‰æ¥åˆ›å¾åQŒåƈ½Ž€å•地包装了HTTPçš„ServletRequeståQŒServletResponseå’ŒFilterChain。FilterInvocation可以用来保护HTTP资源。通常åQŒå¼€å‘ähå‘˜åÆˆä¸éœ€è¦äº†è§£å®ƒçš„å·¥ä½œæœºåˆÓž¼Œå› äؓ他们只需要将Filter加入web.xmlåQŒAcegi安全¾pȝ»Ÿž®±å¯ä»¥å·¥ä½œäº†ã€?br /><br /><b>安全配置参数</b><br />       每个安全½Ž¡ç†å¯¹è±¡éƒ½å¯ä»¥æ˜q°æ•°é‡ä¸é™çš„各种安全认证è¯äh±‚。例如,MethodInvocation对象可以描述带有ä»ÀL„å‚æ•°çš„ä“Q意方法的调用åQŒè€ŒFilterInvocation可以描述ä»ÀL„çš„HTTP URLã€?br />       Acegi安全¾pȝ»Ÿéœ€è¦è®°å½•应用于每个认证è¯äh±‚的安全配¾|®å‚数。例如,对于BankManager.getBalanceåQˆint accountNumberåQ‰æ–¹æ³•å’ŒBankManager.approveLoanåQˆint applicationNumberåQ‰æ–¹æ³•,它们需要的认证è¯äh±‚的安全配¾|®å¾ˆä¸ç›¸åŒã€?br />       ä¸ÞZº†ä¿å­˜ä¸åŒçš„认证请求的安全配置åQŒéœ€è¦ä‹É用配¾|®å‚数。从实现的视角来看,配置参数使用ConfigAttribute接口来表½Cºã€‚Acegi安全¾pȝ»Ÿæä¾›äº†ConfigAttribute接口的一个实玎ͼŒSecurityConfigåQŒå®ƒæŠŠé…¾|®å‚æ•îC¿å­˜äؓ一个字½W¦ä¸²ã€?br />       ConfigAttributeDefinition¾cÀL˜¯ConfigAttribute对象的一个简单的容器å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å’ŒCredentialåQ?br />      2 然后¾pȝ»Ÿè®¤è¯Principalå’ŒCredential信息åQ?br />      3 如果认证通过åQŒç³»¾lŸå–出Principal的授权信息;<br />      4 接下来,客户端发èµäh“ä½œè¯·æ±‚ï¼›<br />      5 ¾pȝ»Ÿæ ÒŽ®é¢„先配置的参数检查Principal对于该操作的授权åQ?br />      6 如果授权‹‚€æŸ¥é€šè¿‡åˆ™æ‰§è¡Œæ“ä½œï¼Œå¦åˆ™æ‹’绝ã€?br />      那么åQŒAcegi安全¾pȝ»Ÿæ˜¯å¦‚何完成这些工作的呢?首先åQŒæˆ‘们来看看Acegi安全¾pȝ»Ÿçš„认证和授权的相关类åQ?<br />      安全拦截器的抽象基类åQŒå®ƒåŒ…含有两个管理类åQŒAuthenticationManagerå’ŒAccessDecisionManager。AuthenticationManager用于认证ContextHolder中的Authentication对象åQˆåŒ…含了PrincipalåQŒCredentialå’ŒPrincipal的授权信息)åQ›AccessDecissionManager则用于授权一个特定的操作ã€?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 />      上面的配¾|®æ–‡ä»¶ä¸­åQŒMethodSecurityInterceptor是AbstractSecurityInterceptor的一个实现类。它包含了两个管理器åQŒauthenticationManagerå’Œ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. 用户ç™Õd½•¾pȝ»ŸåQŒAcegi从acegisecurity.ui子系¾lŸçš„安全拦截器(如BasicProcessingFilteråQ‰ä¸­å¾—到用户的登录信息(包括Principalå’ŒCredentialåQ‰åƈ攑օ¥Authentication对象åQŒåƈ保存在ContextHolder对象中;<br />       2. 安全拦截器将Authentication对象交给AuthenticationManager˜q›è¡Œíw«ä†¾è®¤è¯åQŒå¦‚果认证通过åQŒè¿”回带有Principal授权信息的Authentication对象。此时ContextHolder对象的Authentication对象已拥有Principal的详¾l†ä¿¡æ¯ï¼›<br />       3. 用户ç™Õd½•成功后,¾l§ç®‹˜q›è¡Œä¸šåŠ¡æ“ä½œåQ?br />       4. 安全拦截器(bankManagerSecurityåQ‰æ”¶åˆ°å®¢æˆïL«¯æ“ä½œè¯äh±‚后,ž®†æ“ä½œè¯·æ±‚的数据包装成安全管理对象(FilterInvocation或MethodInvocation对象åQ‰ï¼›<br />       5. 然后åQŒä»Žé…ç½®æ–‡äšgåQˆObjectDefinitionSourceåQ‰ä¸­è¯Õd‡ºç›¸å…³çš„安全配¾|®å‚æ•°ConfigAttributeDefinitionåQ?br />       6. 接着åQŒå®‰å…¨æ‹¦æˆªå™¨å–出ContextHolder中的Authentication对象åQŒæŠŠå®ƒä¼ é€’ç»™AuthenticationManager˜q›è¡Œíw«ä†¾è®¤è¯åQŒåƈ用返回值更新ContextHolderçš„Authentication对象åQ?br />       7. ž®†Authentication对象åQŒConfigAttributeDefinition对象和安全管理对象(secure ObjectåQ‰äº¤¾l™AccessDecisionManageråQŒæ£€æŸ¥Principal的操作授权;<br />       8. 如果授权‹‚€æŸ¥é€šè¿‡åˆ™æ‰§è¡Œå®¢æˆïL«¯è¯äh±‚的操作,否则拒绝åQ?br /><br /><b>AccessDecisionVoter</b><br />       注意上节的accessDecisionManager是一个AffirmativeBased¾c»ï¼Œå®ƒå¯¹äºŽç”¨æˆähŽˆæƒçš„æŠ•ç¥¨½{–略是,只要通过其中的一个授权投¼œ¨æ£€æŸ¥ï¼Œå›_¯é€šè¿‡åQ›å®ƒçš„allowIfAllAbstainDecisions属性值是falseåQŒæ„æ€æ˜¯å¦‚果所有的授权投票是都是弃权,则通不˜q‡æŽˆæƒæ£€æŸ¥ã€?br />       Acegi安全¾pȝ»ŸåŒ…括了几个基于投¼œ¨ç­–略的AccessDecisionManageråQŒä¸ŠèŠ‚çš„RoleVoterž®±æ˜¯å…¶ä¸­çš„一个投¼œ¨ç­–略实玎ͼŒå®ƒæ˜¯AccessDecisionVoter的一个子¾c…R€‚AccessDecisionVoter的具体实现类通过投票来进行授权决½{–,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”回int˜q”回å€û|¼Œå®ƒä»¬æ˜¯AccessDecisionVoter的三个静态成员属性:ACCESS_ABSTAIN,åQŒACCESS_DENIEDå’ŒACCESS_GRANTEDåQŒå®ƒä»¬åˆ†åˆ«æ˜¯å¼ƒæƒåQŒå¦å†›_’Œèµžæˆã€?br />       Acegi安全¾pȝ»Ÿä¸­ï¼Œä½¿ç”¨æŠ•票½{–略的AccessDecisionManager共有三个具体实现¾c»ï¼šAffirmativeBased、ConsensusBasedå’ŒUnanimousBased。它们的投票½{–略是,AffirmativeBased¾cÕdªéœ€æœ‰ä¸€ä¸ªæŠ•¼œ¨èµžæˆå³å¯é€šè¿‡åQ›ConsensusBased¾c»éœ€è¦å¤§å¤šæ•°æŠ•票赞成卛_¯é€šè¿‡åQ›è€ŒUnanimousBased¾c»éœ€è¦æ‰€æœ‰çš„æŠ•票赞成才能通过ã€?br />       RoleVoter¾cÀL˜¯ä¸€ä¸ªAcegi安全¾pȝ»ŸAccessDecisionVoter接口的实现。如果ConfigAttribute以ROLE_å¼€å¤ß_¼ŒRoleVoter则进行投¼œ¨ã€‚如果GrantedAuthorityçš„getAutorityæ–ÒŽ³•çš„String˜q”回值匹配一个或多个以ROLE_开头的ConfigAttributeåQŒåˆ™æŠ•票通过åQŒå¦åˆ™ä¸é€šè¿‡ã€‚如果没有以ROLE_开头的ConfigAttributeåQŒRoleVoter则弃权ã€?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å’ŒLayoutåQŒLog4j 允许开发äh员定义多个LoggeråQŒæ¯ä¸ªLogger拥有自己的名字,Logger之间通过名字来表明隶属关¾p…R€‚有一个Logger¿UîCØ“RootåQŒå®ƒæ°¸è¿œ 存在åQŒä¸”不能通过名字‹‚€ç´¢æˆ–引用åQŒå¯ä»¥é€šè¿‡Logger.getRootLogger()æ–ÒŽ³•获得åQŒå…¶å®ƒLogger通过 Logger.getLogger(String name)æ–ÒŽ³•ã€?br />   Appender则是用来指明ž®†æ‰€æœ‰çš„log信息存放åˆîC»€ä¹ˆåœ°æ–¹ï¼ŒLog4j中支持多¿UappenderåQŒå¦‚ console、files、GUI components、NT Event Loggers½{‰ï¼Œä¸€ä¸ªLogger可以拥有多个AppenderåQŒä¹Ÿž®±æ˜¯ä½ æ—¢å¯ä»¥ž®†Log信息输出到屏òq•,同时存储åˆîC¸€ä¸ªæ–‡ä»¶ä¸­ã€?br />   Layout的作用是控制Log信息的输出方式,也就是格式化输出的信息ã€?br />   Log4j中将要输出的Log信息定义äº?¿Uçñ”别,依次为DEBUG、INFO、WARN、ERRORå’ŒFATALåQŒå½“输出æ—Óž¼Œåªæœ‰¾U§åˆ«é«˜è¿‡é…ç½®ä¸­è§„定的 ¾U§åˆ«çš„信息才能真正的输出åQŒè¿™æ ·å°±å¾ˆæ–¹ä¾¿çš„æ¥é…¾|®ä¸åŒæƒ…况下要输出的内容åQŒè€Œä¸éœ€è¦æ›´æ”¹ä»£ç ï¼Œ˜q™ç‚¹å®žåœ¨æ˜¯æ–¹ä¾¿å•Šã€?br /><br />2、Log4j的配¾|®æ–‡ä»?br />  虽然可以不用配置文äšgåQŒè€Œåœ¨½E‹åºä¸­å®žçŽ°é…¾|®ï¼Œä½†è¿™¿Uæ–¹æ³•在如今的系¾lŸå¼€å‘中昄¡„¶æ˜¯ä¸å¯å–的,能采用配¾|®æ–‡ä»¶çš„地方一定一定要用配¾|®æ–‡ä»¶ã€‚Log4j支持ä¸?¿Uæ ¼å¼çš„配置文äšgåQšXML格式和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Œæ˜¯è®„¡½®rootåQŒæ ¼å¼äØ“ log4j.rootLogger=[level],appenderName, ...åQŒå…¶ä¸­levelž®±æ˜¯è®„¡½®éœ€è¦è¾“å‡ÞZ¿¡æ¯çš„¾U§åˆ«åQŒåŽé¢æ˜¯appender的输出的目的圎ͼŒappenderNamež®±æ˜¯æŒ‡å®šæ—¥å¿—信息输出到哪个地斏V€‚您可以同时指定多个输出目的地。配¾|®æ—¥å¿—信息输出目的地AppenderåQŒå…¶è¯­æ³•ä¸?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.ConsoleAppenderåQˆæŽ§åˆ¶å°åQ?br />  org.apache.log4j.FileAppenderåQˆæ–‡ä»Óž¼‰<br />  org.apache.log4j.DailyRollingFileAppenderåQˆæ¯å¤©äñ”生一个日志文ä»Óž¼‰<br />  org.apache.log4j.RollingFileAppenderåQˆæ–‡ä»¶å¤§ž®åˆ°è¾¾æŒ‡å®šå°ºå¯¸çš„æ—¶å€™äñ”生新文äšgåQ?br />  org.apache.log4j.WriterAppenderåQˆå°†æ—¥å¿—信息以流格式发送到ä»À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.HTMLLayoutåQˆä»¥HTML表格形式布局åQ‰ï¼Œ<br />  org.apache.log4j.PatternLayoutåQˆå¯ä»¥çµ‹zÕdœ°æŒ‡å®šå¸ƒå±€æ¨¡å¼åQ‰ï¼Œ<br />  org.apache.log4j.SimpleLayoutåQˆåŒ…含日志信息的¾U§åˆ«å’Œä¿¡æ¯å­—½W¦ä¸²åQ‰ï¼Œ<br />  org.apache.log4j.TTCCLayoutåQˆåŒ…含日志äñ”生的旉™—´ã€çº¿½E‹ã€ç±»åˆ«ç­‰½{‰ä¿¡æ¯ï¼‰ <br /><br />3、Log4j在程序中的ä‹Éç”?br />  要在自己的类中ä‹É用Log4jåQŒé¦–先声明一个静态变量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提供的范例JPetStore¾l™äº†ä¸€äº›è¿™æ–šw¢çš„介¾lï¼Œä½†è¿˜˜qœè¿œä¸å¤ŸåQŒAcegiæ˜¯ä¸€ä¸ªä¸“é—¨äØ“SpringFramework提供安全机制çš?™å¹ç›®åQŒå…¨¿UîCØ“Acegi Security System for SpringåQŒå½“å‰ç‰ˆæœ¬äØ“0.5.1åQŒå°±å…¶ç›®å‰æä¾›çš„功能åQŒåº”该可以满­‘³ç»å¤§å¤šæ•°åº”用的需求ã€?br /><br />本文的主要目的是希望能够说明如何在基于Spring构架的Web应用中ä‹É用AcegiåQŒè€Œä¸æ˜¯è¯¦¾l†ä»‹¾lå…¶ä¸­çš„æ¯ä¸ªæŽ¥å£ã€æ¯ä¸ªç±»ã€‚注意,即ä‹É对已¾lå­˜åœ¨çš„Spring应用åQŒé€šè¿‡ä¸‹é¢ä»‹ç»çš„æ­¥éª¤ï¼Œä¹Ÿå¯ä»¥é©¬ä¸Šäín受到Acegi提供的认证和授权ã€?br /><br />[基础工作]<br />在你的Web应用的lib中添加Acegi下蝲包中的acegi-security.jar<br /><br />[web.xml]<br />实现认证和授权的最常用的方法是通过filteråQŒAcegi亦是如此åQŒé€šå¸¸Acegi需要在web.xmlæ·ÕdР以䏋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.FilterToBeanProxyåQŒAcegi自己的文档上解释是: “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) 如果你的应用不需要安全传输,如httpsåQŒåˆ™ž®?Acegi Channel Processing Filter"相关内容注释掉即可;<br />3) 如果你的应用不需要Spring提供的远½E‹è®¿é—®æœºåˆÓž¼Œå¦‚Hessian and BurlapåQŒå°†"Acegi HTTP BASIC Authorization <br />Filter"相关内容注释掉即可ã€?br /><br />[applicationContext.xml]<br />接下来就是要æ·ÕdŠ applicationContext.xml中的内容了,从刚才FilterToBeanFactory的解释可以看出,真正的filteréƒ?br />在Springçš„applicationContext中管理:<br /><br />1) 首先åQŒä½ çš„æ•°æ®åº“中必™åÕd…·æœ‰ä¿å­˜ç”¨æˆ·åå’Œå¯†ç çš„tableåQŒAcegi要求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çš„jdbcDaoåQŒå¦‚下:<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) æ·ÕdŠ DaoAuthenticationProvider:<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>åQŒAcegi提供了几¿UåŠ å¯†æ–¹æ³•ï¼Œè¯¦ç»†æƒ…å†µå¯çœ‹åŒ?br />net.sf.acegisecurity.providers.encoding<br /><br />4) æ·ÕdŠ authenticationManager:<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) æ·ÕdŠ accessDecisionManager:<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) æ·ÕdŠ authenticationProcessingFilterEntryPoint:<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) æ·ÕdŠ filterInvocationInterceptor:<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) æ·ÕdŠ securityEnforcementFilter:<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) æ·ÕdŠ authenticationProcessingFilter:<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Œé™¤æ­¤ä¹‹å¤–,Acegi˜q˜æä¾›äº†å¦å¤–一个Interceptor―â€?br />MethodSecurityInterceptoråQŒå®ƒ¾l“合runAsManager可实现对对象中的æ–ÒŽ³•的权限控åˆÓž¼Œä½¿ç”¨æ–ÒŽ³•可参看Acegi自带的文æ¡?br />å’Œcontact范例ã€?br /><br />[最后要说的]<br />æœ¬æ¥ä»¥äØ“åªæ˜¯è¯´æ˜Žå¦‚ä½•ä½¿ç”¨Acegi而已åQŒåº”该非常简单,但真正写èµäh¥æ‰å‘现想要条理清楚的理顺所有需要的bean˜q˜æ˜¯å¾?br />困难的,但愿我没有遗漏太多东西,如果我的文章有什么遗漏或错误的话åQŒè¿˜è¯·å‚看Acegi自带的quick-start范例åQŒä½†è¯?br />注意åQŒè¿™ä¸ªèŒƒä¾‹æ˜¯ä¸èƒ½ç›´æŽ¥æ‹¿æ¥ç”¨çš„ã€?br />分析和学习Spring中的jpetstore用户½Ž¡ç† <br />  存在用户的系¾lŸï¼Œå¿…然需要用æˆïLš„ç™Õd½•和认证,今天ž®±é€šè¿‡åˆ†æžSpring中自带的jpetstore的例子来学习一下如何实现在Spring构架的系¾lŸä¸­ç”¨æˆ·ç™Õd½•ã€?br />1、首先从注册用户开始,先看看jpetstore-servlet.xml中关于注册用æˆïLš„bean定义å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ŒåŽŸæ¥äØ“EditAccountFormåQ›Â Â?br />2). EditoAccountForm.jspä¸­æ˜¾å¾—éžå¸æ€Ø•åQŒå…¶å®žæ²¡æœ‰å¤šž®‘难理解的地方,最主要的是˜q™ä¸ªform既是æ·ÕdŠ æ–°ç”¨æˆïLš„åQŒåˆæ˜¯ç¼–辑用户信息的åQŒæ‰€ä»¥æ˜¾å¾—æœ‰ç‚¹äØ•¾pŸç³Ÿçš„ã€?br />2、添加好了新用户åQŒæŽ¥ä¸‹æ¥çœ‹çœ‹å¦‚何ç™Õd½•åQŒåœ¨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è¡Œæ—¶ç”¨æˆ¯‚¾“入用户名和密码的formåQŒå«åšSignonFormåQŒå¯¹äºŽè¿™ä¸?ParameterizableViewControlleråQŒç”¨æ–‡æ¡£é‡Œçš„话说˜q™æ˜¯æœ€½Ž€å•çš„ControlleråQŒå…¶ä½œç”¨ž®±æ˜¯åœ¨è¿è¡Œä¸­æŒ‡å‘ Controller而不是直接指向jspæ–‡äšgåQŒä»…此而已ã€?br />2). SignonForm.jspåQŒé‡Œé¢å°±æ˜¯ä¸€ä¸ªç®€å•çš„formåQŒå…¶actionž®±æ˜¯½W¬ä¸€ä¸ªbeanåQŒå³/shop/signon.doåQŒæœ€éœ€è¦æ³¨æ„çš„æ˜?signonForwardActionåQŒå…¶ä¸»è¦ä½œç”¨æ˜¯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实现了preHandleåQŒå› æ­¤åœ¨è¯äh±‚上面的map™åµé¢æ—Óž¼Œé¦–先要经˜q‡è¿™ä¸ªInterceptoråQŒçœ‹çœ?SignonInterceptorçš„æºç ï¼ŒåŽŸæ¥åœ¨å…¶ä¸­äØ“signon.jsp赋予一个signonForwardAction对象åQŒå‘µå‘µï¼Œæ€È®—明白了ã€?br />3). 接下来去学习一下SignonControlleråQŒå…¶ä¸ÖM½“部分中可以看出,首先取出用户输入的usernameå’ŒpasswordåQŒç„¶åŽåˆ°æ•°æ®åº“中验证 æœ‰æ²¡æœ‰è¿™ä¸ªç”¨æˆøP¼Œå¦‚果没有˜q™ä¸ªç”¨æˆ·åQŒè¿”回各错误™åµé¢åQ›å¦‚果成功,首先生成一个UserSession对象åQŒåœ¨requestçš„session加入˜q™ä¸ª userSessionåQŒæ³¨æ„è¿™éƒ¨åˆ†ä»£ç ä¸­ç»™å‡ÞZº†PagedListHolder分页的简单ä‹É用方法,关于分页昄¡¤ºåQŒä»¥åŽå†å­¦ä¹ å§ã€?br />3、登录成功后åQŒå°±å¯ä»¥æ ÒŽ®ä¸åŒçš„用戯‚®¾æ–½ä¸åŒçš„è¡ŒäØ“äº†ï¼Œå–å¾—ç”¨æˆ·ä¿¡æ¯åQŒæ— éžå°±æ˜¯ä»Žsession取出userSession卛_¯ã€?br /></div><img src ="http://www.aygfsteel.com/mkchen/aggbug/90397.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/mkchen/" target="_blank">‹¹äh€?/a> 2006-12-27 23:20 <a href="http://www.aygfsteel.com/mkchen/archive/2006/12/27/90397.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title> [转]软äšg‹¹‹è¯•工程师面试问é¢?http://www.aygfsteel.com/mkchen/archive/2006/12/24/89795.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sun, 24 Dec 2006 14:49:00 GMThttp://www.aygfsteel.com/mkchen/archive/2006/12/24/89795.htmlhttp://www.aygfsteel.com/mkchen/comments/89795.htmlhttp://www.aygfsteel.com/mkchen/archive/2006/12/24/89795.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/89795.htmlhttp://www.aygfsteel.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-模式开发方法,你是否认同这个模型?
    什么是CMMåQŸä½ å·¥ä½œ˜q‡çš„公司的çñ”别是怎么æ ïLš„åQ?
    什么才½Ž—好的测试ä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ˆè¯¥æ–‡è{载自MatrixåQŒåŽŸæ–‡åœ°å€åQ?a >http://www.matrix.org.cn/resource/article/44/44430_software+test.htmlåQ?/p>

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



    ]]>
    [转]Java 5.0多线½E‹ç¼–½E?http://www.aygfsteel.com/mkchen/archive/2006/12/24/89792.html‹¹äh€?/dc:creator>‹¹äh€?/author>Sun, 24 Dec 2006 14:37:00 GMThttp://www.aygfsteel.com/mkchen/archive/2006/12/24/89792.htmlhttp://www.aygfsteel.com/mkchen/comments/89792.htmlhttp://www.aygfsteel.com/mkchen/archive/2006/12/24/89792.html#Feedback1http://www.aygfsteel.com/mkchen/comments/commentRss/89792.htmlhttp://www.aygfsteel.com/mkchen/services/trackbacks/89792.html阅读全文

    ]]>
    利用XMLBean轻轻松松è¯Õd†™XMLhttp://www.aygfsteel.com/mkchen/archive/2006/12/21/89382.html‹¹äh€?/dc:creator>‹¹äh€?/author>Thu, 21 Dec 2006 15:10:00 GMThttp://www.aygfsteel.com/mkchen/archive/2006/12/21/89382.htmlhttp://www.aygfsteel.com/mkchen/comments/89382.htmlhttp://www.aygfsteel.com/mkchen/archive/2006/12/21/89382.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/89382.htmlhttp://www.aygfsteel.com/mkchen/services/trackbacks/89382.html 利用XMLBean轻轻松松è¯Õd†™XML
    作者:叶枫




    版权声明å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方式存储çš? XML˜q˜åº”ç”?br />于Java Message Serviceå’ŒWeb Services½{‰æŠ€æœ¯ä½œä¸ºæ•°æ®äº¤æ?
    å› æ­¤,正确è¯Õd†™XML文档是XML应用的基¼‹€.
      Java提供了SAXå’ŒDOM两种方式用于解析XML,但即便如æ­?要读写一ä¸?br />½Eå¾®å¤æ‚çš„XML,也不是一件容易的äº?

    二、XMLBean½Ž€ä»?/span>

        Hibernateå·²ç»æˆäØ“ç›®å‰‹¹è¡Œçš„面向Java环境的对è±?关系数据库映ž®„å·¥å…?
    在Hibernate½{‰å¯¹è±?关系数据库映ž®„工具出çŽîC¹‹å‰?å¯ÒŽ•°æ®åº“的操作是
    通过JDBC来实现的,å¯ÒŽ•°æ®åº“çš„ä“Q何操ä½?开发äh员都要自己写SQL语句
    来实çŽ? 对象/关系数据库映ž®„工具出现后,å¯ÒŽ•°æ®åº“的操作è{成对
    JavaBean的操�极大方便了数据库开� 所以如果有一个类似的工具能够
    实现ž®†å¯¹XML的读写è{成对JavaBean的操ä½?ž®†ä¼š½Ž€åŒ–XML的读å†?即ä‹É对XML
    不熟悉的开发äh员也能方便地è¯Õd†™XML. ˜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,和地址2¾l„成.
    其中帐单地址˜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¦æŸ,比如数据¾cÕdž‹½{? 利用˜q™ä¸ªSchemaæ–‡äšg,XMLBeanž®†ä¼šäº§ç”Ÿ
           一¾pÕdˆ—相关的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æ–‡äšgè¯Õd†™XML.

    五、利用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è¡Œä¹‹åŽ,我们ž®†ä¼šçœ‹åˆ°å®¢æˆ·¾~–号ä¸?的客æˆïLš„lastnameå·²ç»æ”¹äØ“last.

    八、利用XMLBean删除一个customer

        再增加一个Method:
        

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

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


             main method:
        

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

            
    ˜qè¡Œ,我们ž®†ä¼šçœ‹åˆ°å®¢æˆ·¾~–号ä¸?的客æˆïLš„资料已经被删é™?

    九、查询XML

        除了本文在以上讲˜q°çš„,利用XMLBean能轻è½ÀL¾æ‘Ö®ŒæˆXML的读写操作外,¾l“合XPathå’ŒXQuery,
       XMLBean˜q˜èƒ½å®Œæˆè±¡SQL查询数据库一æ äh–¹ä¾¿åœ°æŸ¥è¯¢XML数据. 关于XML查询以及如何创徏XML数据åº? 我将在另一½‹‡æ–‡ç« é‡Œè®¨è®º.



    十、结束语
        XMLBean能帮助我们轻易读写XML,˜q™å°†æœ‰åŠ©äºŽæˆ‘ä»¬é™ä½ŽXML的学习和使用,有了˜q™ä¸ªåŸºç¡€,
        开发äh员将为学习更多地XML相关技术和Web Services,JMS½{‰å…¶ä»–J2EE技术打下良好地基础.


    关于作者:
    叶枫åQšçƒ­çˆ±Javaå’ŒOracle. 在èÊY件开发有˜q?0òq? 目前在国外一家美国大公司担ä“QSA, 负责技术研½I¶ã€‚作者BlogåQ?a target="_new">http://blog.matrix.org.cn/page/叶枫

    ]]>
    ¾~–写你自å·Þqš„单点ç™Õd½•åQˆSSOåQ‰æœåŠ?/title><link>http://www.aygfsteel.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://www.aygfsteel.com/mkchen/archive/2006/12/21/89377.html</guid><wfw:comment>http://www.aygfsteel.com/mkchen/comments/89377.html</wfw:comment><comments>http://www.aygfsteel.com/mkchen/archive/2006/12/21/89377.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/mkchen/comments/commentRss/89377.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.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šå•点登录(SSOåQ‰çš„æŠ€æœ¯è¢«­‘Šæ¥­‘Šå¹¿æ³›åœ°˜qç”¨åˆ°å„个领域的软äšg¾pȝ»Ÿå½“中。本...  <a href='http://www.aygfsteel.com/mkchen/archive/2006/12/21/89377.html'>阅读全文</a><img src ="http://www.aygfsteel.com/mkchen/aggbug/89377.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/mkchen/" target="_blank">‹¹äh€?/a> 2006-12-21 22:42 <a href="http://www.aygfsteel.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://www.aygfsteel.com/mkchen/archive/2006/12/21/89366.html‹¹äh€?/dc:creator>‹¹äh€?/author>Thu, 21 Dec 2006 13:47:00 GMThttp://www.aygfsteel.com/mkchen/archive/2006/12/21/89366.htmlhttp://www.aygfsteel.com/mkchen/comments/89366.htmlhttp://www.aygfsteel.com/mkchen/archive/2006/12/21/89366.html#Feedback0http://www.aygfsteel.com/mkchen/comments/commentRss/89366.htmlhttp://www.aygfsteel.com/mkchen/services/trackbacks/89366.html
      2、出生日期码表示¾~–码对象出生的年、月、日åQŒæŒ‰GB/T7408的规定执行。年、月、日代码之间不用分隔½W¦ã€‚例åQšæŸäººå‡ºç”Ÿæ—¥æœŸäØ“1966òq?0æœ?6日,其出生日期码ä¸?9661026ã€?br />
      3、顺序码表示在同一地址码所标识的区域范围内åQŒå¯¹åŒå¹´ã€åŒæœˆã€åŒæ—¥å‡ºç”Ÿçš„人编定的™åºåºåøP¼Œ™åºåºç çš„奇数分配¾l™ç”·æ€§ï¼Œå¶æ•°åƒåˆ†é…ç»™å¥Ïx€§ã€?br />
      4、校验码校验码采用ISO7064åQ?983åQŒMOD11-2校验码系¾lŸã€?br />
      1åQ‰åä¸ƒä½æ•°å­—本体码加权求和公式 S=Sum(Ai*Wi),i=0,...,16åQŒå…ˆå¯¹å‰17位数字的权求和 Ai:表示½W¬i位置上的íw«ä†¾è¯å·ç æ•°å­—倹{€€Wi:表示½W¬i位置上的加权因子 Wi:7910584216379105842

      2åQ‰è®¡½Ž—模 Y=mod(S,11)

      3åQ‰é€šè¿‡æ¨¡å¾—到对应的校验码 :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());}}


    ]]>
    Ö÷Õ¾Ö©Öë³ØÄ£°å£º ÒÁÄþÊÐ| ³½ÏªÏØ| ÃÉÉ½ÏØ| Ë³Æ½ÏØ| ÌÁ¹ÁÇø| ¶¼²ýÏØ| µÃÈÙÏØ| ÑÎÉ½ÏØ| äàË®ÏØ| ÁÙëÔÏØ| »¸Ì¨ÏØ| ¶ýÔ´ÏØ| ¸®¹ÈÏØ| ¶«Ïç×å×ÔÖÎÏØ| »¸ÈÊ| ÉîÔóÏØ| ÁÙ·ÚÊÐ| ÂÐÆ½ÏØ| ÏåÔ«ÏØ| ¾°Ì©ÏØ| °×ÒøÊÐ| ¹ãÖÝÊÐ| Îå³£ÊÐ| ºáÉ½ÏØ| À³Î÷ÊÐ| ͳ·¬ÊÐ| Áé´¨ÏØ| ÄÂÀâÊÐ| ÁúÁêÏØ| ½­Î÷Ê¡| ËçÑôÏØ| ʯ³ÇÏØ| ¶¼½­ÑßÊÐ| ±¾ÏªÊÐ| ¼ªÊ×ÊÐ| éŽ­ÏØ| Âò³µ| ÁøÁÖÏØ| ÌìÕòÏØ| ÇàÌïÏØ| ¶î¶û¹ÅÄÉÊÐ|