??xml version="1.0" encoding="utf-8" standalone="yes"?>
1、FACTORY—追MM不了请吃饭了,麦当劳的鸡翅和肯德基的鸡都是MM爱吃的东西,虽然口味有所不同Q但不管你带MM去麦当劳或肯德基Q只向服务员说“来四个鸡翅”就行了。麦当劳和肯德基是生鸡翅的Factory
工厂模式Q客L和工厂类分开。消费者Q何时候需要某U品,只需向工厂请求即可。消费者无M改就可以接纳C品。缺Ҏ当品修ҎQ工厂类也要做相应的修改。如Q如何创建及如何向客L提供?
2、BUILDER—MM最爱听的就是“我׃”这句话了,见到不同地方的MM,要能够用她们的方a跟她说这句话哦,我有一个多U语a译机,上面每种语言都有一个按键,见到MM我只要按对应的键Q它p够用相应的语a说出“我׃”这句话了,国外的MM也可以轻松搞掂,q就是我的“我׃”builder。(q一定比军在伊拉克用的译机好卖)
建造模式:品的内部表象和品的生成q程分割开来,从而一个徏造过E生成具有不同的内部表象的品对象。徏造模式得品内部表象可以独立的变化Q客户不必知道品内部组成的l节。徏造模式可以强制实行一U分步骤q行的徏造过E?
3、FACTORY METHOD—请MM去麦当劳吃汉堡,不同的MM有不同的口味Q要每个都记住是一件烦人的事情Q我一般采用Factory Method模式Q带着MM到服务员那儿Q说“要一个汉堡”,具体要什么样的汉堡呢Q让MM直接跟服务员说就行了?
工厂Ҏ模式Q核心工厂类不再负责所有品的创徏Q而是具体创建的工作交给子类dQ成Z个抽象工厂角Ԍ仅负责给出具体工厂类必须实现的接口,而不接触哪一个品类应当被实例化q种l节?
4、PROTOTYPE—跟MM用QQ聊天Q一定要说些深情的话语了Q我搜集了好多肉ȝ情话Q需要时只要copy出来攑ֈQQ里面p了,q就是我的情话prototype了。(100块钱一份,你要不要Q?
原始模型模式Q通过l出一个原型对象来指明所要创建的对象的类型,然后用复制这个原型对象的Ҏ创徏出更多同cd的对象。原始模型模式允许动态的增加或减品类Q品类不需要非得有M事先定的等U结构,原始模型模式适用于Q何的{l构。缺Ҏ每一个类都必配备一个克隆方法?
5、SINGLETON—俺?个漂亮的老婆Q她们的老公都是我,我就是我们家里的老公SigletonQ她们只要说道“老公”,都是指的同一个hQ那是?刚才做了个梦啦,哪有q么好的?
单例模式Q单例模式确保某一个类只有一个实例,而且自行实例化ƈ向整个系l提供这个实例单例模式。单例模式只应在有真正的“单一实例”的需求时才可使用?
l构型模?
6、ADAPTER—在朋友聚会上碰C一个美女SarahQ从香港来的Q可我不会说_语Q她不会说普通话Q只好求助于我的朋友kent了,他作为我和Sarah之间的AdapterQ让我和Sarah可以怺交谈?也不知道他会不会耍我)
适配器(变压器)模式Q把一个类的接口变换成客户端所期待的另一U接口,从而原本因接口原因不匚w而无法一起工作的两个c能够一起工作。适配cd以根据参数返q一个合适的实例l客L?
7、BRIDGE—早上碰到MMQ要说早上好Q晚上碰到MMQ要说晚上好Q碰到MMI了件新衣服Q要说你的衣服好漂亮哦,到MM新做的发型,要说你的头发好漂亮哦。不要问我“早上碰到MM新做了个发型怎么说”这U问题,自己用BRIDGEl合一下不p?
桥梁模式Q将抽象化与实现化脱耦,使得二者可以独立的变化Q也是说将他们之间的强兌变成弱关联,也就是指在一个Y件系l的抽象化和实现化之间用组?聚合关系而不是承关p,从而两者可以独立的变化?
8、COMPOSITE—Mary今天q生日。“我q生日,你要送我一件礼物。”“嗯Q好吧,d店,你自己挑。”“这件T恤挺漂亮Q买Q这条裙子好看,乎ͼq个包也不错Q买。”“喂Q买了三件了呀Q我只答应送一件礼物的哦。”“什么呀QT恤加裙子加包包,正好配成一套呀Q小姐,ȝ你包h。”“……”,MM都会用Composite模式了,你会了没有?
合成模式Q合成模式将对象l织到树l构中,可以用来描述整体与部分的关系。合成模式就是一个处理对象的树结构的模式。合成模式把部分与整体的关系用树l构表示出来。合成模式得客L把一个个单独的成分对象和׃们复合而成的合成对象同{看待?
9、DECORATOR—Maryq完轮到Sarlyq生日,q是不要叫她自己挑了Q不然这个月伙食费肯定玩完,拿出我去q在华山上照的照片Q在背面写上“最好的的礼物,是׃的Fita”,再到街上C品店买了个像框Q卖C品的MM也很漂亮哦)Q再N壁搞术设计的Mike设计了一个漂亮的盒子装v来……,我们都是DecoratorQ最l都在修饰我q个人呀Q怎么P看懂了吗Q?
装饰模式Q装饰模式以对客L透明的方式扩展对象的功能Q是l承关系的一个替代方案,提供比承更多的灉|性。动态给一个对象增加功能,q些功能可以再动态的撤消。增加由一些基本功能的排列l合而生的非常大量的功能?/p>
10、FACADE—我有一个专业的Nikon相机Q我喜Ƣ自己手动调光圈、快门,q样照出来的照片才专业,但MM可不懂这些,教了半天也不会。幸好相机有Facade设计模式Q把相机调整到自动档Q只要对准目标按快门p了,一切由相机自动调整Q这样MM也可以用q个相机l我拍张照片了?
门面模式Q外部与一个子pȝ的通信必须通过一个统一的门面对象进行。门面模式提供一个高层次的接口,使得子系l更易于使用。每一个子pȝ只有一个门面类Q而且此门面类只有一个实例,也就是说它是一个单例模式。但整个pȝ可以有多个门面类?
11、FLYWEIGHT—每天跟MM发短信,手指都篏MQ最q买了个新手机,可以把一些常用的句子存在手机里,要用的时候,直接拿出来,在前面加上MM的名字就可以发送了Q再不用一个字一个字敲了。共享的句子是FlyweightQMM的名字就是提取出来的外部特征Q根据上下文情况使用?
享元模式QFLYWEIGHT在拳L赛中指最轻量U。n元模式以׃n的方式高效的支持大量的细_度对象。n元模式能做到׃n的关键是区分内蕴状态和外蕴状态。内蕴状态存储在享元内部Q不会随环境的改变而有所不同。外蕴状态是随环境的改变而改变的。外蕴状态不能媄响内蕴状态,它们是相互独立的。将可以׃n的状态和不可以共享的状态从常规cM区分开来,不可以׃n的状态从c里剔除出去。客L不可以直接创׃n的对象,而应当用一个工厂对象负责创׃n的对象。n元模式大q度的降低内存中对象的数量?
12、PROXY—跟MM在网上聊天,一开头L“hi,你好?“你从哪儿来呀Q”“你多大了?”“n高多呀Q”这些话Q真烦hQ写个程序做为我的Proxy吧,凡是接收到这些话都设|好了自动的回答Q接收到其他的话时再通知我回{,怎么P酷吧?
代理模式Q代理模式给某一个对象提供一个代理对象,q由代理对象控制Ҏ对象的引用。代理就是一个h或一个机构代表另一个h或者一个机构采取行动。某些情况下Q客户不x者不能够直接引用一个对象,代理对象可以在客户和目标对象直接起到中介的作用。客L分L不出代理主题对象与真实主题对象。代理模式可以ƈ不知道真正的被代理对象,而仅仅持有一个被代理对象的接口,q时候代理对象不能够创徏被代理对象,被代理对象必Lpȝ的其他角色代为创建ƈ传入?
行ؓ模式
13、CHAIN OF RESPONSIBLEITY—晚上去上英语课Qؓ了好开溜坐C最后一排,哇,前面坐了好几个漂亮的MM哎,扑ּU条Q写上“Hi,可以做我的女朋友吗?如果不愿意请向前传”,U条׃个接一个的传上MQ糟p,传到W一排的MM把纸条传l老师了,听说是个老处奛_Q快?
责Q链模式:在责任链模式中,很多对象由每一个对象对其下家的引用而接
h形成一条链。请求在q个链上传递,直到链上的某一个对象决定处理此h。客户ƈ不知道链上的哪一个对象最l处理这个请求,pȝ可以在不影响客户端的情况下动态的重新l织铑֒分配责Q。处理者有两个选择Q承担责L者把责Q推给下家。一个请求可以最l不被Q何接收端对象所接受?
14、COMMAND—俺有一个MM安得特别严,没法见面Q只好借助于她弟弟在我们俩之间传送信息,她对我有什么指C,写一张纸条让她弟弟带l我。这不,她弟弟又传送过来一个COMMANDQؓ了感谢他Q我请他吃了杂酱面Q哪知道他说Q“我同时l我姐姐三个h友送COMMANDQ就C最气Q才h吃面。”,:-(
命o模式Q命令模式把一个请求或者操作封装到一个对象中。命令模式把发出命o的责d执行命o的责d割开Q委z不同的对象。命令模式允许请求的一方和发送的一方独立开来,使得h的一方不必知道接收请求的一方的接口Q更不必知道h是怎么被接Ӟ以及操作是否执行Q何时被执行以及是怎么被执行的。系l支持命令的撤消?
15、INTERPRETER—俺有一个《MM真经》,上面有各UMM的攻略,比如说去吃西的步骤、去看电qҎ{等Q跟MMU会Ӟ只要做一个InterpreterQ照着上面的脚本执行就可以了?
解释器模式:l定一个语a后,解释器模式可以定义出其文法的一U表C,q同时提供一个解释器。客L可以使用q个解释器来解释q个语言中的句子。解释器模式描q怎样在有了一个简单的文法后,使用模式设计解释q些语句。在解释器模式里面提到的语言是指M解释器对象能够解释的Ml合。在解释器模式中需要定义一个代表文法的命ocȝ{l构Q也是一pd的组合规则。每一个命令对象都有一个解释方法,代表对命令对象的解释。命令对象的{l构中的对象的Q何排列组合都是一个语a?
16、ITERATOR—我׃了MaryQ不一切的向她求婚?
MaryQ“想要我跟你l婚Q得{应我的条g?
我:“什么条件我都答应,你说吧?
MaryQ“我看上了那个一克拉的钻石?
我:“我乎ͼ我买Q还有吗Q?
MaryQ“我看上了湖边的那栋别墅?
我:“我乎ͼ我买Q还有吗Q?
MaryQ“你的小弟弟必须要有50cm镎?
我脑袋嗡的一壎ͼ坐在椅子上,一咬牙Q“我剪,我剪Q还有吗Q?
…?
q代子模式:q代子模式可以顺序访问一个聚集中的元素而不必暴露聚集的内部表象。多个对象聚在一起Ş成的MUC集,聚集对象是能够包容一l对象的容器对象。P代子模式P代逻辑装C个独立的子对象中Q从而与聚集本n隔开。P代子模式化了聚集的界面。每一个聚集对象都可以有一个或一个以上的q代子对象,每一个P代子的P代状态可以是彼此独立的。P代算法可以独立于聚集角色变化?
17、MEDIATOR—四个MM打麻,怺之间谁应该给谁多钱不清楚了,q怺当时我在旁边Q按照各自的{码数算钱,赚了q从我q里拿,赔了q也付l我Q一切就OK啦,俺得C四个MM的电话?
调停者模式:调停者模式包装了一pd对象怺作用的方式,使得q些对象不必怺明显作用。从而他们可以松散偶合。当某些对象之间的作用发生改变时Q不会立卛_响其他的一些对象之间的作用。保证这些作用可以彼此独立的变化。调停者模式将多对多的怺作用转化Z对多的相互作用。调停者模式将对象的行为和协作抽象化,把对象在尺度的行ؓ上与其他对象的相互作用分开处理?
18、MEMENTO—同时跟几个MM聊天Ӟ一定要记清楚刚才跟MM说了些什么话Q不然MM发现了会不高兴的哦,q怺我有个备忘录Q刚才与哪个MM说了什么话我都拯一份放到备忘录里面保存Q这样可以随时察看以前的记录啦?
备忘录模式:备忘录对象是一个用来存储另外一个对象内部状态的快照的对象。备忘录模式的用意是在不破坏装的条件下Q将一个对象的状态捉住,q外部化Q存储v来,从而可以在来合适的时候把q个对象q原到存储v来的状态?
19、OBSERVER—想知道׃公司最新MM情报吗?加入公司的MM情报邮gl就行了Qtom负责搜集情报Q他发现的新情报不用一个一个通知我们Q直接发布给邮gl,我们作ؓ订阅者(观察者)可以及时收到情报啦
观察者模式:观察者模式定义了一U一队多的依赖关p,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化Ӟ会通知所有观察者对象,使他们能够自动更新自己?
20、STATE—跟MM交往Ӟ一定要注意她的状态哦Q在不同的状态时她的行ؓ会有不同Q比如你U她今天晚上ȝ电媄Q对你没兴趣的MM׃说“有事情啦”,对你不讨厌但q没喜欢上的MM׃说“好啊,不过可以带上我同事么Q”,已经喜欢上你的MM׃说“几炚wQ看完电影再L吧怎么P”,当然你看电媄q程中表现良好的话,也可以把MM的状态从不讨厌不喜欢变成喜欢哦?
状态模式:状态模式允怸个对象在其内部状态改变的时候改变行为。这个对象看上去象是改变了它的类一栗状态模式把所研究的对象的行ؓ包装在不同的状态对象里Q每一个状态对象都属于一个抽象状态类的一个子cR状态模式的意图是让一个对象在其内部状态改变的时候,其行Z随之改变。状态模式需要对每一个系l可能取得的状态创立一个状态类的子cR当pȝ的状态变化时Q系l便改变所选的子类?/p>
21、STRATEGY—跟不同cd的MMU会Q要用不同的{略Q有的请电媄比较好,有的则去吃小吃效果不错,有的LvҎ漫最合适,单目的都是ؓ了得到MM的芳心,我的qMM锦囊中有好多Strategy哦?
{略模式Q策略模式针对一l算法,每一个算法封装到h共同接口的独立的cMQ从而得它们可以相互替换。策略模式得算法可以在不媄响到客户端的情况下发生变化。策略模式把行ؓ和环境分开。环境类负责l持和查询行为类Q各U算法在具体的策略类中提供。由于算法和环境独立开来,法的增减,修改都不会媄响到环境和客L?
22、TEMPLATE METHOD——看q《如何说服女生上床》这部经典文章吗Q女生从认识C床的不变的步骤分为y遇、打破僵局、展开q求、接吅R前戏、动手、爱抚、进d大步?Template method)Q但每个步骤针对不同的情况,都有不一L做法Q这p看你随机应变?具体实现)Q?
模板Ҏ模式Q模板方法模式准备一个抽象类Q将部分逻辑以具体方法以及具体构造子的Ş式实玎ͼ然后声明一些抽象方法来q子类实现剩余的逻辑。不同的子类可以以不同的方式实现q些抽象ҎQ从而对剩余的逻辑有不同的实现。先制定一个顶U逻辑框架Q而将逻辑的细节留l具体的子类d现?
23、VISITOR—情CQ要l每个MM送一束鲜花和一张卡片,可是每个MM送的花都要针对她个h的特点,每张卡片也要Ҏ个h的特Ҏ挑,我一个h哪搞得清楚,q是找花店老板和礼品店老板做一下VisitorQ让花店老板ҎMM的特炚w一束花Q让C品店老板也根据每个h特点选一张卡Q这样就L多了Q?
讉K者模式:讉K者模式的目的是封装一些施加于某种数据l构元素之上的操作。一旦这些操作需要修改的话,接受q个操作的数据结构可以保持不变。访问者模式适用于数据结构相Ҏ定的pȝQ它把数据结构和作用于结构上的操作之间的耦合解脱开Q得操作集合可以相对自q演化。访问者模式得增加新的操作变的很ҎQ就是增加一个新的访问者类。访问者模式将有关的行为集中到一个访问者对象中Q而不是分散到一个个的节点类中。当使用讉K者模式时Q要尽可能多的对象览逻辑攑֜讉K者类中,而不是放到它的子cM。访问者模式可以跨q几个类的等U结构访问属于不同的{l构的成员类?/p>
?a >http://java.ccidnet.com/art/3749/20060622/586221_3.html
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
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"
. 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.
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.
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.
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 thatFigure 3 Creating objects with the simple definitionsjane
is an instance ofEngineer
. 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.
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 = "";The
mark.dept = "general";
mark.projects = [];
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"];
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
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 == "";Notice that with these definitions, you cannot specify an initial value for an inherited property such as
jane.dept == "general";
jane.projects == [];
jane.machine == "belau"
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
Engineer
constructor:
function Engineer (name, projs, mach) {Assume we create a new
this.base = WorkerBee;
this.base(name, "engineering", projs);
this.projects = mach || "";
}
Engineer
object as follows:
jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");JavaScript follows these steps:
1. First, thenew
operator creates a generic object and sets its__proto__
property toEngineer.prototype
.
2. Thenew
operator then passes the new object to theEngineer
constructor as the value of thethis
keyword.
3. Next, the constructor creates a new property calledbase
for that object and assigns the value of theWorkerBee
constructor to thebase
property. This makes theWorkerBee
constructor a method of theEngineer
object.
NOTE: The name of thebase
property is not special. You can use any legal property name;base
is simply evocative of its purpose.
4. Next, the constructor calls thebase
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 allEngineer
objects have the same value for the inheriteddept
property and this value overrides the value inherited fromEmployee
.
5. Becausebase
is a method ofEngineer
, within the call tobase
, JavaScript binds thethis
keyword to the object created in step 1. Thus, theWorkerBee
function in turn passes the"Doe, Jane"
and["navigator", "javascript"]
arguments to theEmployee
constructor function. Upon return from theEmployee
constructor function, theWorkerBee
function uses the remaining argument to set theprojects
property.
6. Upon return from thebase
method, theEngineer
constructor initializes the object'smachine
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) {The
this.base = WorkerBee;
this.base(name, "engineering", projs);
this.projects = mach || "";
}
jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
Employee.prototype.specialty = "none";
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) {Now the value of the
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";
jane
object's specialty
property is "none"
.
__proto__
property). function Employee () {
this.name = "";
this.dept = "general";
}
function WorkerBee () {With these definitions, assume you create
this.projects = [];
}
WorkerBee.prototype = new Employee;
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 == "";Now assume you change the value of the
amy.dept = "general";
amy.projects == [];
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.
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;Given this, you could write an
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;
instanceOf
function as follows:
function instanceOf(object, constructor) {With this definition, the following expressions are all true:
while (object != null) {
if (object == constructor.prototype)
return true;
object = object.__proto__;
}
return false;
}
instanceOf (chris, Engineer)But this expression is false:
instanceOf (chris, WorkerBee)
instanceOf (chris, Employee)
instanceOf (chris, Object)
instanceOf (chris, SalesPerson)
Employee
:
var idCounter = 1;
function Employee (name, dept) {With this definition, when you create a new
this.name = name || "";
this.dept = dept || "general";
this.id = idCounter++;
}
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) {When you create an instance of
this.name = name || "";
this.dept = dept || "general";
if (name)
this.id = idCounter++;
}
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.
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"So
dennis.dept == "engineering"
dennis.projects == ["collabra"]
dennis.machine == "hugo"
dennis.hobby == "scuba"
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
研究~程语言中的“丑鸭?/p>
![]() |
|
U别: 初
Bruce Tate
(bruce.tate@j2life.com), 总裁, RapidRed
2007 q?1 ?18 ?/p>
JavaScript 常被Z认ؓ是编E语a中无重的一员。这U观点的形成可以“归功”于其开发工兗复杂且不一致的面向 HTML 面的文档对象模型以及不一致的览器实现。但 JavaScript l对不仅仅是一个玩兯么简单。在本文中,Bruce Tate 向您介绍?JavaScript 的语aҎ?
几乎每个 Web 开发h员都曾有q诅?JavaScript 的经历。这个备受争议的语言受篏于其复杂的称为文档对象模?(DOM)的编E模型、糟p的实现和调试工具以及不一致的览器实现。直到最q,很多开发h员还认ؓ Javascript 从最好的斚w说是无可避免之灾,从最坏的斚w说不q是一U玩LŞ了?
然?JavaScript 现在开始日益重要v来,而且成ؓ了广泛应用于 Web 开发的脚本语言。JavaScript 的复苏一些业界领袖h物也不得不开始重新审视这U编E语a。诸?Ajax (Asynchronous JavaScript + XML) q样的编E技术让 Web |页更加qh。而完整的 Web 开发框Ӟ比如 Apache CocoonQ则?JavaScript 的应用越来越多,使其不只限于是一U用于制?Web 面的简单脚本。JavaScript 的一U称?ActionScript 的派生物也推动了 Macromedia ?Flash 客户端框架的发展。运行在 JVM 上的实现 Rhino ?JavaScript 成ؓ?Java?开发h员所首选的一c脚本语aQ参?参考资?/font>Q?
我的好友兼同?Stuart Halloway ?Ajax 斚w的专Ӟ曑֜其教授的 JavaScript 评中做q这L开场白Q“到 2011 q_JavaScript 被公认为是一U拥有开发现代应用程序所需的一整套新特性的语言?。他l而介l说 JavaScript E序要比cM?Java E序紧密十倍,ql展CZ使其之所以如此的一些语aҎ?
![]() |
|
在这文章中Q我带您探I?JavaScript 的一些特性,看看q些Ҏ如何让它如此具有吸引力Q?
您可能已l熟悉动态类型模型、高阶函数Ş式的函数式编E以及开攑֯象模型这些概念,因ؓ我在其他?i>跨越边界 pd文章中已l作q相关的介绍。如果您从未q行qQ何正式的 JavaScript 开发,您很可能会认些特性属于非常复杂的语言Q例?Python、Lisp、Smalltalk ?HaskellQ而绝非像 JavaScript q样的语a所能提供的。因此,我将用实际的代码CZ来说明这些概c?
您无需讄 JavaScript。如果您可以在浏览器中阅L文章,p明您已经准备qA了。本文包含的所有编E示例都可以在大多数览器内q行。我使用的是 Firefox?
用在 <script type='text/javascript'>
?</script>
标记之间所包含?JavaScript 加蝲单的 Web 面。清?1 可以昄 Hello, World 文本Q?
<script type='text/javascript'> alert('Hello, World.') </script> |
要运行此代码Q只需创徏一个名?example1.html 的文件。将清单 1 的代码复制到该文件内Qƈ在浏览器中加载此文gQ参?下蝲 部分以获得本文用的所有示?HTML 文gQ。注意到每次重蝲此页面时Q该代码都会立即执行?/p>
alert
是个函数调用Q只有一个字W串作ؓ参数。图 1 昄了由清单 1 中的代码弹出的警告框Q显C文?“Hello, World”。如果代码在 HTML body 之内Q目前ƈ未指定Q?bodyQ但览器能接受不规则的 HTMLQƈ且整个页面都默然作ؓ一?body 被处理)。页面一旦加载,JavaScript ׃立即执行?
如果要gq执行,可以?HTML <head>
元素声明 JavaScript 函数Q如清单 2 所C:
<head> <script type='text/javascript'> function hello() { alert('Hello, World.') } </script> </head> <body> <button onclick="hello();">Say Hello</button> </body> |
清?2 中的代码输入C?HTML 文gQ在览器内加蝲该文Ӟ单击 Say Hello 按钮Q结果如?2 所C:
![]() ![]() |
![]()
|
?清单 2Q可以大致体会到一?JavaScript 在操U函数方面的能力。将函数名称传递给 HTML button
标记q利?HTML 的内|事件模型。?JavaScript Ӟ我会l常在变量或数组中存储函敎ͼ在本文后面的 对象模型 一节,您会看到 JavaScript 对象模型{略大量使用了此技巧)。例如,查看一下清?3Q?
<head> <script type='text/javascript'> hot = function hot() { alert('Sweat.') } cold = function cold() { alert('Shiver.') } function swap() { temp = hot hot = cold cold = temp alert('Swapped.') } </script> </head> <body> <button onclick="hot();">Hot</button> <button onclick="cold();">Cold</button> <button onclick="swap();">Swap</button> </body> |
函数?JavaScript 中的一cd象,可以自由地操U它们。首先我声明两个函数Q?code>hot ?cold
。ƈ分别在不同的变量存储它们。单?Hot ?Cold 按钮会调用对应的函数Q生成一个告警。接下来Q声明另一个函数用来交?Hot ?Cold 按钮的|此函数与第三个按钮兌Q该按钮昄如图 3 所C的告警Q?
q个例子说明可以像处理其他变量一样处理函数。C 开发h员很Ҏ此概念看作?i>函数指针 功能Q但 JavaScript 的高阶函数的功能更ؓ强大。该Ҏ让 JavaScript E序员能够像处理其他变量cd一栯村֤理动作或函数?/p>
函数用作函数的参数Q或函C为D回,q些概念属于高阶函数的领域。清?4 ?清单 3 做了一点点修改Q显CZ能返回函数的高阶函数Q?/p>
清单 4. 高阶函数
<head> <script type='text/javascript'> function temperature() { return current } hot = function hot() { alert('Hot.') } cold = function cold() { alert('Cold.') } current = hot function swap() { if(current == hot) { current = cold } else { current = hot } } </script> </head> <body> <button onclick="funct = temperature()();">Temperature</button> <button onclick="swap();">Swap</button> </body> |
q个例子解决了一个常见问题:如何更改中的行为附加到用户接口事gQ通过高阶函数Q这很容易做到?code>temperature 高阶函数q回 current
的|?current 又可以有 hot
?cold
函数。看一下这个有些陈旧的函数调用Q?code>temperature()()。第一l括L于调?temperature
函数。第二组括号调用?temperature
q回 的函数。图 4 昄了输出:
高阶函数是函数式~程的基Q对比面向对象编E,函数式编E代表了更高U别的抽象。但 JavaScript 的实力ƈ不仅限于高阶函数。JavaScript 的动态类型就极ؓ适合 UI 开发?/p>
![]() ![]() |
![]()
|
通过静态类型,~译器可以检查参数和变量的值或针对一个给定操作所允许的返回倹{其优势是编译器可以做额外的错误查。而且静态类型还可以?IDE q样的工h供更多信息,带来其他一些特性,比如更好的代码完成功能。但静态类型也存在着如下一些劣势:
静态类型更适合用于构徏中间件或操作pȝ的语a中。UI 开发常帔R要更高的效率和灵zL,所以更适合采用动态类型。我qq种做法存在危险。相信用过 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>
JavaScript q不会报?blue
属性不存在的错误。静态类型的拥护者大都会被本例所吓倒,因ؓ本例中的错误被很好地隐匿了。虽然这U做法多会让您感觉有些不正当,但您也不能否认它巨大的诱惑力。您可以很快引入属性。如果将本例和本文之前的例子l合hQ还可以引入行ؓ。记住,变量可以保存函数Q所以,Z动态类型和高阶函数Q您可以在Q何时候向cM引入L的行为?
可以L地重?清单 5Q其如清单 6 所C:
<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>
![]() ![]() |
![]()
|
到目前ؓ止,您应该对 JavaScript 有一个正的评h了,它绝非只如一个玩具那么简单。事实上Q很多h都用过其对象模型创极ؓ复杂、设计良好的面向对象软g。但对象模型其是用于承的对象模型又非您一贯认为的那样?
Java 语言是基于类的。当构徏应用E序Ӟ也同时构Z可以作ؓ所有对象的模板的新cR然后调?new
来实例化该模板,创徏一个新对象。而在 JavaScript 中,所创徏的是一个原型,此原型是一个实例,可以创徏所有未来的对象?
现在先暂且放下这些抽象的概念Q去查看一些实际代码。比如,清单 7 创徏了一个简单的 Animal
Q它h name
属性和 speak
动作。其他动物会从这个基l承?
<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:
对于 Java 开发h员而言Q清?7 中的代码看v来多有点生疏和奇怪。实际上对于没有亲自构徏q对象的许多 JavaScript 开发h员来_q些代码同样看v来有点生疏和奇怪。也许,下面的解释可以让大家能够更好地理解这D代码?
实际上,您只需重点x其中三段信息。首先,JavaScript 用嵌套函数表C对象。这意味着清单 7 中的 Animal
的定义是一U有效的语法。第二,JavaScript Z原型或现有的对象的实例来构造对象,而非ZcLѝ?code>funct() 是一U调用,?new Animal()
却基?Animal
内的原型构造一个对象。最后,?JavaScript 中,对象只是函数和变量的集合。每个对象ƈ不与cd相关Q所以可以自由地修改q种l构?
回到 清单 7。如您所见,JavaScript Z?Animal
中指定的原型定义一个新对象Q?code>myAnimal。而可以用原型中的属性和函数Q甚或重定义函数和属性。这U灵zL可能会?Java 开发h员受不了Q因Z们不习惯q种行ؓQ但它的是一U十分强大的模型?/p>
现在我还要更深入一步。您q可以用名?prototype
实例变量来指定对象的基础。方法是讄 prototype
实例变量使其指向l承铄父。如此设|?prototype
之后Q您所创徏的对象会为未指定的那些对象承属性和函数。这样一来,您就可以模仿面向对象的承概c以清单 8 ZQ?
<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承
q也展示?JavaScript 是如何解军_属性或Ҏ的引用问题的Q?/p>
prototype
的实例变量,JavaScript ׃在此实例中寻找Q何未定义的实例变量或属性。这U查找是递归的:如果 ?prototype
内定义的实例不能扑ֈ属性或函数Q它׃?i>?/i> 原型中查找,依此cL?那么QJavaScript 的承模型到底是什么样的?q取决于您如何对它进行定义。您需要定义承行Z便可以覆盖它。然而,从本质上ԌJavaScript 更像是一U函数式语言Q而非面向对象的语aQ它使用一些智能的语法和语义来仿真高度复杂的行为。其对象模型极ؓ灉|、开攑֒强大Q具有全部的反射性。有些h可能会说它太q灵zR而我的忠告则是,按具体作业的需要选择合适的工具?/p>
![]() ![]() |
![]()
|
JavaScript 对象模型构徏在该语言的其他功能之上来支持大量的库Q比?DojoQ参?参考资?/font>Q。这U灵zL让每个框架能够以一U精l的方式更改对象模型。在某种E度上,q种灉|性是一U极大的~点。它可以D可怕的互操作性问题(管该语a的灵zL可以部分缓解这些问题)?
而另一斚wQ灵zL又是一U巨大的优势。Java 语言一直苦于无法充分增强其灉|性,原因是它的基本对象模型还未灵zd可以被扩展的E度。一个典型的企业U开发h员ؓ能够成功使用 Java 语言必须要学习很多东西,而新出现的一些优U的开放源码项目和新技术,比如面向斚w~程、Spring ~程框架和字节码增强库,则带来了大量要学的代码?
最后,JavaScript 优秀的灵zL的让您体会到了一些高阶语a的强大功能。当然您无需选择为每个项目或大多数项目都做这L权衡和折街但了解一U语a的优势和劣势 —?通过参考大量信息,而不仅仅Zq告宣传或公众意?—?会让您可以更好地控制何时需要用以及何时不能用这U语a。当您在修改 JavaScript Web 部件时Q您臛_知道该如何让此语a发挥它最大的优势。请l箋跨越边界吧?/p>
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--删除游标引用
<bean id="bankManagerSecurity"
class="net.sf.acegisecurity.intercept.method.MethodSecurityInterceptor">
<property name="validateConfigAttributes">
<value>true</value>
</property>
<property name="authenticationManager">
<ref bean="authenticationManager"/>
</property>
<property name="accessDecisionManager">
<ref bean="accessDecisionManager"/>
</property>
<property name="objectDefinitionSource">
<value>
net.sf.acegisecurity.context.BankManager.delete*=
ROLE_SUPERVISOR,RUN_AS_SERVER
net.sf.acegisecurity.context.BankManager.getBalance=
ROLE_TELLER,ROLE_SUPERVISOR,BANKSECURITY_CUSTOMER,RUN_
</value>
</property>
</bean>
<bean id="authenticationDao" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="daoAuthenticationProvider"
class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="authenticationDao"><ref bean="authenticationDao"/></property>
</bean>
<bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
<property name="providers">
<list><ref bean="daoAuthenticationProvider"/></list>
</property>
</bean>
<bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>
<bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions"><value>false</value></property>
<property name="decisionVoters">
<list><ref bean="roleVoter"/></list>
</property>
</bean>
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
import com.foo.Bar;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class MyApp {
static Logger logger = Logger.getLogger(MyApp.class.getName());
public static void main(String[] args) {
// BasicConfigurator replaced with PropertyConfigurator.
PropertyConfigurator.configure(args[0]);
logger.info("Entering application.");
Bar bar = new Bar();
bar.doIt();
logger.info("Exiting application.");
}
}
<filter>
<filter-name>Acegi Channel Processing Filter</filter-name>
<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>net.sf.acegisecurity.securechannel.ChannelProcessingFilter</param-value>
</init-param>
</filter>
<filter>
<filter-name>Acegi Authentication Processing Filter</filter-name>
<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter</param-value>
</init-param>
</filter>
<filter>
<filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>net.sf.acegisecurity.ui.basicauth.BasicProcessingFilter</param-value>
</init-param>
</filter>
<filter>
<filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
<filter-class>net.sf.acegisecurity.ui.AutoIntegrationFilter</filter-class>
</filter>
<filter>
<filter-name>Acegi HTTP Request Security Filter</filter-name>
<filter-class>net.sf.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Acegi Channel Processing Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Acegi Authentication Processing Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Acegi HTTP BASIC Authorization Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Acegi Security System for Spring Auto Integration Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Acegi HTTP Request Security Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
CREATE TABLE users (
username VARCHAR(50) NOT NULL PRIMARY KEY,
password VARCHAR(50) NOT NULL,
enabled BIT NOT NULL
);
CREATE TABLE authorities (
username VARCHAR(50) NOT NULL,
authority VARCHAR(50) NOT NULL
);
CREATE UNIQUE INDEX ix_auth_username ON authorities ( username, authority );
ALTER TABLE authorities ADD CONSTRAINT fk_authorities_users foreign key (username) REFERENCES users
(username);
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="jdbcDaoImpl" class="net.sf.acegisecurity.providers.dao.jdbc.JdbcDaoImpl">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<bean id="daoAuthenticationProvider" class="net.sf.acegisecurity.providers.dao.DaoAuthenticationProvider">
<property name="authenticationDao"><ref bean="authenticationDao"/></property>
<property name="userCache"><ref bean="userCache"/></property>
</bean>
<bean id="userCache" class="net.sf.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
<property name="minutesToIdle"><value>5</value></property>
</bean>
<bean id="authenticationManager" class="net.sf.acegisecurity.providers.ProviderManager">
<property name="providers">
<list>
<ref bean="daoAuthenticationProvider"/>
</list>
</property>
</bean>
<bean id="accessDecisionManager" class="net.sf.acegisecurity.vote.AffirmativeBased">
<property name="allowIfAllAbstainDecisions">
<value>false</value>
</property>
<property name="decisionVoters">
<list><ref bean="roleVoter"/></list>
</property>
</bean>
<bean id="roleVoter" class="net.sf.acegisecurity.vote.RoleVoter"/>
<bean id="authenticationProcessingFilterEntryPoint"
class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilterEntryPoint">
<property name="loginFormUrl"><value>/acegilogin.jsp</value></property>
<property name="forceHttps"><value>false</value></property>
</bean>
<%@ taglib prefix='c' uri='http://java.sun.com/jstl/core' %>
<%@ page import="net.sf.acegisecurity.ui.AbstractProcessingFilter" %>
<%@ page import="net.sf.acegisecurity.AuthenticationException" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="<c:url value='j_acegi_security_check'/>" method="POST">
<table>
<tr><td>User:</td><td><input type='text' name='j_username'></td></tr>
<tr><td>Password:</td><td><input type='password' name='j_password'></td></tr>
<tr><td colspan='2'><input name="submit" type="submit"></td></tr>
<tr><td colspan='2'><input name="reset" type="reset"></td></tr>
</table>
</form>
</body>
</html>
<bean id="filterInvocationInterceptor"
class="net.sf.acegisecurity.intercept.web.FilterSecurityInterceptor">
<property name="authenticationManager">
<ref bean="authenticationManager"/>
</property>
<property name="accessDecisionManager">
<ref bean="accessDecisionManager"/>
</property>
<property name="objectDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
\A/sec/administrator.*\Z=ROLE_SUPERVISOR
\A/sec/user.*\Z=ROLE_TELLER
</value>
</property>
</bean>
<bean id="securityEnforcementFilter" class="net.sf.acegisecurity.intercept.web.SecurityEnforcementFilter">
<property name="filterSecurityInterceptor">
<ref bean="filterInvocationInterceptor"/>
</property>
<property name="authenticationEntryPoint">
<ref bean="authenticationProcessingFilterEntryPoint"/>
</property>
</bean>
<bean id="authenticationProcessingFilter"
class="net.sf.acegisecurity.ui.webapp.AuthenticationProcessingFilter">
<property name="authenticationManager">
<ref bean="authenticationManager"/>
</property>
<property name="authenticationFailureUrl">
<value>/loginerror.jsp</value>
</property>
<property name="defaultTargetUrl">
<value>/</value>
</property>
<property name="filterProcessesUrl">
<value>/j_acegi_security_check</value>
</property>
</bean>
<bean id="channelProcessingFilter" class="net.sf.acegisecurity.securechannel.ChannelProcessingFilter">
<property name="channelDecisionManager">
<ref bean="channelDecisionManager"/>
</property>
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
\A/sec/administrator.*\Z=REQUIRES_SECURE_CHANNEL
\A/acegilogin.jsp.*\Z=REQUIRES_SECURE_CHANNEL
\A/j_acegi_security_check.*\Z=REQUIRES_SECURE_CHANNEL
\A.*\Z=REQUIRES_INSECURE_CHANNEL
</value>
</property>
</bean>
<bean id="channelDecisionManager" class="net.sf.acegisecurity.securechannel.ChannelDecisionManagerImpl">
<property name="channelProcessors">
<list>
<ref bean="secureChannelProcessor"/>
<ref bean="insecureChannelProcessor"/>
</list>
</property>
</bean>
<bean id="secureChannelProcessor" class="net.sf.acegisecurity.securechannel.SecureChannelProcessor"/>
<bean id="insecureChannelProcessor" class="net.sf.acegisecurity.securechannel.InsecureChannelProcessor"/>
<bean name="/shop/newAccount.do" class="org.springframework.samples.jpetstore.web.spring.AccountFormController">
<property name="petStore"><ref bean="petStore"/></property>
<property name="validator"><ref bean="accountValidator"/></property>
<property name="successView"><value>index</value></property>
</bean>
<bean name="/shop/signon.do" class="org.springframework.samples.jpetstore.web.spring.SignonController">
<property name="petStore"><ref bean="petStore"/></property>
</bean>
<bean name="/shop/signonForm.do" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName"><value>SignonForm</value></property>
</bean>
<bean id="secureHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="signonInterceptor"/>
</list>
</property>
<property name="urlMap">
<map>
<entry key="/shop/editAccount.do"><ref local="secure_editAccount"/></entry>
<entry key="/shop/listOrders.do"><ref local="secure_listOrders"/></entry>
<entry key="/shop/newOrder.do"><ref local="secure_newOrder"/></entry>
<entry key="/shop/viewOrder.do"><ref local="secure_viewOrder"/></entry>
</map>
</property>
</bean>
Q该文{载自MatrixQ原文地址Q?a >http://www.matrix.org.cn/resource/article/44/44430_software+test.htmlQ?/p>
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=791907
<?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>
<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>
<?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>
scomp [options] [dirs]* [schemaFile.xsd]* [service.wsdl]* [config.xsdconfig]*
scomp -src build\src -out build\customerXmlBean.jar schema\customer.xsd
-compiler C:\jdk142_04\bin\javac customer.xsdconfig
CustomersDocument.java -- 整个XML文档的Java Class映射
CustomerType.java -- 节点sustomer的映?br /> AddressType.java -- 节点address的映?br /> BillingAddressType.java -- 节点billingAddress的映?br /> PrimaryAddressType.java -- 节点primaryAddress的映?br />
package com.sample.reader;
import java.io.File;
import sample.xmlbean.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.xmlbeans.XmlOptions;
public class CustomerXMLBean {
private String filename = null;
public CustomerXMLBean(String filename) {
super();
this.filename = filename;
}
public void customerReader() {
try {
File xmlFile = new File(filename);
CustomersDocument doc = CustomersDocument.Factory.parse(xmlFile);
CustomerType[] customers = doc.getCustomers().getCustomerArray();
for (int i = 0; i < customers.length; i++) {
CustomerType customer = customers[i];
println("Customer#" + i);
println("Customer ID:" + customer.getId());
println("First name:" + customer.getFirstname());
println("Last name:" + customer.getLastname());
println("Gender:" + customer.getGender());
println("PhoneNumber:" + customer.getPhoneNumber());
// Primary address
PrimaryAddressType primaryAddress = customer.getAddress().getPrimaryAddress();
println("PrimaryAddress:");
println("PostalCode:" + primaryAddress.getPostalCode());
println("AddressLine1:" + primaryAddress.getAddressLine1());
println("AddressLine2:" + primaryAddress.getAddressLine2());
// Billing address
BillingAddressType billingAddress = customer.getAddress().getBillingAddress();
println("BillingAddress:");
println("Receiver:" + billingAddress.getReceiver());
println("PostalCode:" + billingAddress.getPostalCode());
println("AddressLine1:" + billingAddress.getAddressLine1());
println("AddressLine2:" + billingAddress.getAddressLine2());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void println(String str) {
System.out.println(str);
}
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.customerReader();
}
}
Customer#0
Customer ID:1
First name:Jessica
Last name:Lim
Gender:female
PhoneNumber:1234567
PrimaryAddress:
PostalCode:350106
AddressLine1:#25-1
AddressLine2:SHINSAYAMA 2-CHOME
BillingAddress:
Receiver:Ms Danielle
PostalCode:350107
AddressLine1:#167
AddressLine2:NORTH TOWER HARBOUR CITY
Customer#1
Customer ID:2
First name:David
Last name:Bill
Gender:male
PhoneNumber:808182
PrimaryAddress:
PostalCode:319087
AddressLine1:1033 WS St.
AddressLine2:Tima Road
BillingAddress:
Receiver:Mr William
PostalCode:672993
AddressLine1:1033 WS St.
AddressLine2:Tima Road
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();
}
}
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.createCustomer();
}
<?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>
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();
}
}
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");
}
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();
}
}
public static void main(String[] args) {
String filename = "F://JavaTest//Eclipse//XMLBean//xml//customers_new.xml";
CustomerXMLBean customerXMLBean = new CustomerXMLBean(filename);
customerXMLBean.deleteCustomer(3);
}