版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、thinkinginpatternswith javabruce eckelpresident, mindview, inc.revision 0.4please note that this document is in its initial form, and much remains to be done. corrections and comments should go to contentspreface7introduction91: the pattern concept11what is a pattern?11patterns vs. idioms13the singl
2、eton13classifying patterns15exercises162: unit testing17write tests first18a very simple framework19writing tests21white-box & black-box tests24running tests26automatically executing tests28exercises283: building application frameworks31template method314:fronting for an implementation33proxy34state
3、35statemachine38exercises44x: iterators: decoupling algorithms from containers47type-safe iterators485: factories: encapsulating object creation51simple factory method52polymorphic factories54abstract factories57exercises606: function objects61command61strategy63chain of responsibility65exercises677
4、: changing the interface69adapter69faade71package as a variation of faade72exercises738: table-driven code: configuration flexibility75table-driven code using anonymous inner classes759: interpreter/ multiple languages77interpreter77motivation78python overview79built-in containers80functions81string
5、s82classes83creating a language87configuring jpython90generating documentation91controlling the interpreter91putting data in92getting data out98multiple interpreters101controlling java from jpython102using java libraries105inheriting from java library classes107creating java classes with jpython108b
6、uilding the java classes from the python code113summary114exercises11510: callbacks117observer117observing flowers118a visual example of observers122exercises12511: multiple dispatching127visitor, a type of multiple dispatching130exercises13312: pattern refactoring135simulating the trash recycler135
7、improving the design139“make more objects”140a pattern for prototyping creation143trash subclasses147parsing trash from an external file149recycling with prototyping152abstracting usage154multiple dispatching158implementing the double dispatch159the visitor pattern166a reflective decorator169more co
8、upling?174rtti considered harmful?175summary178exercises17913: projects181rats & mazes181xml decorator186prefaceintroduction1: the pattern conceptthis book introduces the important and yet non-traditional “patterns” approach to program design. probably the most important step forward in object-orien
9、ted design is the “design patterns” movement, chronicled in design patterns, by gamma, helm, johnson & vlissides (addison-wesley, 1995). but be warned: the examples are in c+. that book shows 23 different solutions to particular classes of problems. in this book, the basic concepts of design pattern
10、s will be introduced along with examples. this should whet your appetite to read design patterns by gamma, et. al., a source of what has now become an essential, almost mandatory, vocabulary for oop programmers.the latter part of this book contains an example of the design evolution process, startin
11、g with an initial solution and moving through the logic and process of evolving the solution to more appropriate designs. the program shown (a trash sorting simulation) has evolved over time, and you can look at that evolution as a prototype for the way your own design can start as an adequate solut
12、ion to a particular problem and evolve into a flexible approach to a class of problems.what is a pattern?initially, you can think of a pattern as an especially clever and insightful way of solving a particular class of problems. that is, it looks like a lot of people have worked out all the angles o
13、f a problem and have come up with the most general, flexible solution for it. the problem could be one you have seen and solved before, but your solution probably didnt have the kind of completeness youll see embodied in a pattern.although theyre called “design patterns,” they really arent tied to t
14、he realm of design. a pattern seems to stand apart from the traditional way of thinking about analysis, design, and implementation. instead, a pattern embodies a complete idea within a program, and thus it can sometimes appear at the analysis phase or high-level design phase. this is interesting bec
15、ause a pattern has a direct implementation in code and so you might not expect it to show up before low-level design or implementation (and in fact you might not realize that you need a particular pattern until you get to those phases).the basic concept of a pattern can also be seen as the basic con
16、cept of program design: adding a layer of abstraction. whenever you abstract something youre isolating particular details, and one of the most compelling motivations behind this is to separate things that change from things that stay the same. another way to put this is that once you find some part
17、of your program thats likely to change for one reason or another, youll want to keep those changes from propagating other changes throughout your code. not only does this make the code much cheaper to maintain, but it also turns out that it is usually simpler to understand (which results in lowered
18、costs).often, the most difficult part of developing an elegant and cheap-to-maintain design is in discovering what i call “the vector of change.” (here, “vector” refers to the maximum gradient and not a container class.) this means finding the most important thing that changes in your system, or put
19、 another way, discovering where your greatest cost is. once you discover the vector of change, you have the focal point around which to structure your design.so the goal of design patterns is to isolate changes in your code. if you look at it this way, youve been seeing some design patterns already
20、in this book. for example, inheritance can be thought of as a design pattern (albeit one implemented by the compiler). it allows you to express differences in behavior (thats the thing that changes) in objects that all have the same interface (thats what stays the same). composition can also be cons
21、idered a pattern, since it allows you to changedynamically or staticallythe objects that implement your class, and thus the way that class works.youve also already seen another pattern that appears in design patterns: the iterator (java 1.0 and 1.1 capriciously calls it the enumeration; java 2 conta
22、iners use “iterator”). this hides the particular implementation of the container as youre stepping through and selecting the elements one by one. the iterator allows you to write generic code that performs an operation on all of the elements in a sequence without regard to the way that sequence is b
23、uilt. thus your generic code can be used with any container that can produce an iterator.pattern taxonomyone of the events thats occurred with the rise of design patterns is what could be thought of as the “pollution” of the term people have begun to use the term to mean just about anything synonymo
24、us with “good.” after some pondering, ive come up with a sort of hierarchy describing a succession of different types of categories:1. idiom: how we write code in a particular language to do this particular type of thing. this could be something as common as the way that you code the process of step
25、ping through an array in c (and not running off the end).2. specific design: the solution that we came up with to solve this particular problem. this might be a clever design, but it makes no attempt to be general.3. standard design: a way to solve this kind of problem. a design that has become more
26、 general, typically through reuse.4. design pattern: how to solve an entire class of similar problem. this usually only appears after applying a standard design a number of times, and then seeing a common pattern throughout these applications.i feel this helps put things in perspective, and to show
27、where something might fit. however, it doesnt say that one is better than another. it doesnt make sense to try to take every problem solution and generalize it to a design pattern its not a good use of your time, and you cant force the discovery of patterns that way; they tend to be subtle and appea
28、r over time.one could also argue for the inclusion of analysis pattern and architectural pattern in this taxonomy.the singletonpossibly the simplest design pattern is the singleton, which is a way to provide one and only one object of a particular type. this is used in the java libraries, but heres
29、a more direct example:/: c01:singletonpattern.java/ the singleton design pattern: you can/ never instantiate more than one./ since this isnt inherited from a cloneable/ base class and cloneability isnt added,/ making it final prevents cloneability from/ being added through inheritance:final class si
30、ngleton private static singleton s = new singleton(47); private int i; private singleton(int x) i = x; public static singleton getreference() return s; public int getvalue() return i; public void setvalue(int x) i = x; public class singletonpattern public static void main(string args) singleton s =
31、singleton.getreference(); system.out.println(s.getvalue(); singleton s2 = singleton.getreference(); s2.setvalue(9); system.out.println(s.getvalue(); try / cant do this: compile-time error. / singleton s3 = (singleton)s2.clone(); catch(exception e) e.printstacktrace(system.err); /:the key to creating
32、 a singleton is to prevent the client programmer from having any way to create an object except the ways you provide. you must make all constructors private, and you must create at least one constructor to prevent the compiler from synthesizing a default constructor for you (which it will create as
33、“friendly”).at this point, you decide how youre going to create your object. here, its created statically, but you can also wait until the client programmer asks for one and create it on demand. in any case, the object should be stored privately. you provide access through public methods. here, getr
34、eference() produces the reference to the singleton object. the rest of the interface (getvalue() and setvalue() is the regular class interface.java also allows the creation of objects through cloning. in this example, making the class final prevents cloning. since singleton is inherited directly fro
35、m object, the clone() method remains protected so it cannot be used (doing so produces a compile-time error). however, if youre inheriting from a class hierarchy that has already overridden clone() as public and implemented cloneable, the way to prevent cloning is to override clone() and throw a clo
36、nenotsupportedexception as described in appendix a. (you could also override clone() and simply return this, but that would be deceiving since the client programmer would think they were cloning the object, but would instead still be dealing with the original.)note that you arent restricted to creat
37、ing only one object. this is also a technique to create a limited pool of objects. in that situation, however, you can be confronted with the problem of sharing objects in the pool. if this is an issue, you can create a solution involving a check-out and check-in of the shared objects.classifying pa
38、tternsthe design patterns book discusses 23 different patterns, classified under three purposes (all of which revolve around the particular aspect that can vary). the three purposes are: 1. creational: how an object can be created. this often involves isolating the details of object creation so your
39、 code isnt dependent on what types of objects there are and thus doesnt have to be changed when you add a new type of object. the aforementioned singleton is classified as a creational pattern, and later in this book youll see examples of factory method and prototype.2. structural: designing objects
40、 to satisfy particular project constraints. these work with the way objects are connected with other objects to ensure that changes in the system dont require changes to those connections.3. behavioral: objects that handle particular types of actions within a program. these encapsulate processes tha
41、t you want to perform, such as interpreting a language, fulfilling a request, moving through a sequence (as in an iterator), or implementing an algorithm. this book contains examples of the observer and the visitor patterns.the design patterns book has a section on each of its 23 patterns along with
42、 one or more examples for each, typically in c+ but sometimes in smalltalk. (youll find that this doesnt matter too much since you can easily translate the concepts from either language into java.) this book will not repeat all the patterns shown in design patterns since that book stands on its own
43、and should be studied separately. instead, this book will give some examples that should provide you with a decent feel for what patterns are about and why they are so important.after years of looking at these things, it began to occur to me that the patterns themselves use basic principles of organ
44、ization, other than (and more fundamental than) those described in design patterns. these principles are based on the structure of the implementations, which is where i have seen great similarities between patterns (more than those expressed in design patterns). although we generally try to avoid im
45、plementation in favor of interface, i have found that its often easier to think about, and especially to learn about, the patterns in terms of these structural principles. this book will attempt to present the patterns based on their structure instead of the categories presented in design patterns.e
46、xercises1. singletonpattern.java always creates an object, even if its never used. modify this program to use lazy initialization, so the singleton object is only created the first time that it is needed.2. using singletonpattern.java as a starting point, create a class that manages a fixed number o
47、f its own objects. assume the objects are database connections and you only have a license to use a fixed quantity of these at any one time.2: unit testingone of the important recent realizations is the dramatic value of unit testing.this is the process of building integrated tests into all the code
48、 that you create, and running those tests every time you do a build. its as if you are extending the compiler, telling it more about what your program is supposed to do. that way, the build process can check for more than just syntax errors, since you teach it how to check for semantic errors as wel
49、l.c-style programming languages, and c+ in particular, have typically valued performance over programming safety. the reason that developing programs in java is so much faster than in c+ (roughly twice as fast, by most accounts) is because of javas safety net: features like better type checking, enf
50、orced exceptions and garbage collection. by integrating unit testing into your build process, you are extending this safety net, and the result is that you can develop faster. you can also be bolder in the changes that you make, and more easily refactor your code when you discover design or implemen
51、tation flaws, and in general produce a better product, faster.unit testing is not generally considered a design pattern; in fact, it might be considered a “development pattern,” but perhaps there are enough “pattern” phrases in the world already. its effect on development is so significant that it w
52、ill be used throughout this book, and thus will be introduced here.my own experience with unit testing began when i realized that every program in a book must be automatically extracted and organized into a source tree, along with appropriate makefiles (or some equivalent technology) so that you cou
53、ld just type make to build the whole tree. the effect of this process on the code quality of the book was so immediate and dramatic that it soon became (in my mind) a requisite for any programming bookhow can you trust code that you didnt compile? i also discovered that if i wanted to make sweeping
54、changes, i could do so using search-and-replace throughout the book, and also bashing the code around at will. i knew that if i introduced a flaw, the code extractor and the makefiles would flush it out.as programs became more complex, however, i also found that there was a serious hole in my system
55、. being able to successfully compile programs is clearly an important first step, and for a published book it seemed a fairly revolutionary oneusually due to the pressures of publishing, its quite typical to randomly open a programming book and discover a coding flaw. however, i kept getting message
56、s from readers reporting semantic problems in my code (in thinking in java). these problems could only be discovered by running the code. naturally, i understood this and had taken some early faltering steps towards implementing a system that would perform automatic execution tests, but i had succum
57、bed to the pressures of publishing, all the while knowing that there was definitely something wrong with my process and that it would come back to bite me in the form of embarrassing bug reports (in the open source world, embarrassment is one of the prime motivating factors towards increasing the quality of ones code!).the other problem was that i was lacking a structure for the testing system. eventually, i started hearing about unit testing and junit /homes/jv/cs510/read/junit3.1/, which provided a basis for a test
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024年建筑材料供應(yīng)分包協(xié)議
- 2024年建筑設(shè)計(jì)院與BIM技術(shù)合作服務(wù)協(xié)議
- 2024年幼兒園全職教師協(xié)議
- 2024年工程項(xiàng)目聯(lián)營(yíng)合同
- 2024年企業(yè)市場(chǎng)營(yíng)銷策劃服務(wù)承包合同
- 2024年庫(kù)房租賃與光伏設(shè)備存放合同
- 9A Unit5 Art World(提分小卷)-【單元測(cè)試】(譯林版)(解析版)
- 2024婚介網(wǎng)站服務(wù)合同樣本:會(huì)員隱私保護(hù)與婚配服務(wù)承諾
- 2024年度碳排放權(quán)核查服務(wù)合同
- 2024農(nóng)業(yè)開發(fā)與產(chǎn)品銷售合同
- 餐飲行業(yè)初期投資預(yù)算分析
- 遼寧省重點(diǎn)高中沈陽(yáng)市郊聯(lián)體2023-2024學(xué)年高三上學(xué)期期中生物試題(解析版)
- 退費(fèi)申請(qǐng)表模板(直接打?。?/a>
- 剪映:手機(jī)短視頻制作-配套課件
- 西氣東輸二線25標(biāo)段山嶺隧道內(nèi)管道安裝技術(shù)
- 防校園欺凌-課件(共28張PPT)
- 第6章 智能網(wǎng)聯(lián)汽車測(cè)評(píng)技術(shù)
- 單向板結(jié)構(gòu)設(shè)計(jì)
- 普通高等學(xué)校學(xué)生轉(zhuǎn)學(xué)申請(qǐng)表
- 房租、水、電費(fèi)(專用)收據(jù)Excel模板
- 習(xí)近平總書記關(guān)于教育的重要論述研究學(xué)習(xí)通章節(jié)答案期末考試題庫(kù)2023年
評(píng)論
0/150
提交評(píng)論