Upload
trinhdiep
View
214
Download
2
Embed Size (px)
Citation preview
115-214
SchoolofComputerScience
23Patternsin80Minutes:aWhirlwindJava-centricTouroftheGang-of-FourDesignPatterns
JoshBloch CharlieGarrod
215-214
Administrivia
• Homework6checkpointdue Friday 5pm• Finalexam Tuesday,May3, 5:30-8:30pm,PH100• FinalreviewsessionSunday,May, 7-9pm,DH1112
315-214
KeyconceptfromTuesday…MapReducewithkey/valuepairs(Googlestyle)
• Master– Assigntaskstoworkers– Pingworkerstotestforfailures
• Mapworkers– Mapforeachkey/valuepair
– Emitintermediatekey/valuepairs
the shuffle:
415-214
• E.g.,foreachwordontheWeb,countthenumberoftimesthatwordoccurs§ ForMap:key1 isadocumentname,value isthecontentsofthatdocument
§ ForReduce:key2 isaword,values isalistofthenumberofcountsofthatword
KeyconceptfromTuesday…MapReducewithkey/valuepairs(Googlestyle)
f1(String key1, String value): for each word w in value:
EmitIntermediate(w, 1);
f2(String key2, Iterator values):int result = 0;for each v in values:
result += v;Emit(key2, result);
Map: (key1, v1) à (key2, v2)* Reduce: (key2, v2*) à (key3, v3)*
MapReduce: (key1, v1)* à (key3, v3)*
MapReduce: (docName, docText)* à (word, wordCount)*
615-214
PatternName
• Intent– theaimofthispattern• Usecase– amotivatingexample• Keytypes– theinterfacesthatdefinepattern• JDK– example(s)ofthispatternintheJDK
715-214
Illustration
• Codesample,diagram,ordrawing– Timeconstraintsmakeitimpossibletoincludeillustrationsfromsomepatterns
• SomepatternslackanillustrationL
915-214
AbstractFactory
• Intent– Allowcreationoffamiliesofrelatedobjects independentofimplementation
• Usecase– look-and-feelinaGUItoolkit• Keytype– Factory withmethodstocreateeachfamilymember
• JDK– Notcommon
1015-214
Builder
• Intent– Separateconstructionofcomplexobjectfromrepresentationsosamecreationprocesscancreatedifferentrepresentations
• Usecase– convertingrichtexttovariousformats• Keytypes– (Abstract)Builder– GoF hasextralayerofindirection(“Director”)
• JDK– StringBuilder,StringBuffer*– ButbothproduceString– AndmostbuildersintheJDKareconcrete
1115-214
MytakeonBuilder
• Emulatesnamedparametersinlanguagesthatdon’tsupportthem
• ReducesexponentialO(2n)creationalmethodstoO(n)byallowingthemtobecombinedfreely,atthecostofanintermediate(Builder)object
1215-214
BuilderIllustrationNutritionFacts twoLiterDietCoke = new NutritionFacts.Builder(
"Diet Coke", 240, 8).sodium(1).build();
public class NutritionFacts {public static class Builder {
public Builder(String name, int servingSize, int servingsPerContainer) { ... }
public Builder totalFat(int val) { totalFat = val; }public Builder saturatedFat(int val) { satFat = val; }public Builder transFat(int val) { transFat = val; }public Builder cholesterol(int val) { cholesterol = val; }... // 15 more setters
public NutritionFacts build() {return new NutritionFacts(this);
}}private NutritionFacts(Builder builder) { ... }
}
1315-214
FactoryMethod
• Intent– abstractcreationalmethodthatletssubclassesdecidewhichclasstoinstantiate
• Usecase– creatingdocumentsinaframework• Keytypes– Creator,whichcontainsabstractmethodtocreateaninstance
• JDK– notcommon.Iterable.iterator()• RelatedStaticFactorypatternisverycommon– TechnicallynotaGoF pattern,butcloseenough
1415-214
FactoryMethodIllustrationpublic interface Iterable<E> {
public abstract Iterator<E> iterator();}
public class ArrayList<E> implements List<E> {public Iterator<E> iterator() { ... }...
}
public class HashSet<E> implements Set<E> {public Iterator<E> iterator() { ... }...
}
1515-214
Prototype
• Intent– Createanobjectbycloninganotherandtweakingasnecessary
• Usecase– writingamusicscoreeditorinagraphicaleditorframework
• Keytypes– Prototype(AKACloneable)• JDK– clone,butdon’tuseit(exceptonarrays)– JavaandPrototypepatternareapoorfit
1615-214
Singleton
• Intent– ensuringaclasshasonlyoneinstance• Usecase– GoF sayprintqueue,filesystem,companyinanaccountingsystem– Compellingusesarerarebuttheydoexist
• Keytypes– Singleton• JDK– java.lang.Runtime
1715-214
SingletonIllustrationpublic enum Elvis {
ELVIS;
public sing(Song song) { ... }
public playGuitar(Riff riff) { ... }
public eat(Food food) { ... }
public take(Drug drug) { ... }}
1815-214
Mytakeonsingleton
• It’saninstance-controlled class;othersinclude– Staticutilityclass(non-instantiable)– Enum – oneinstancepervalue,allvaluesknownatcompiletime
– Internedclass– onecanonicalinstancepervalue,newvaluescreatedatruntime
• Thereisadualitybetweensingletonandstaticutilityclass
1915-214
II.StructuralPatterns
1. Adapter2. Bridge3. Composite4. Decorator5. Façade6. Flyweight7. Proxy
2015-214
Adapter
• Intent– convertinterfaceofaclassintoonethatanotherclassrequires,allowinginteroperability
• Usecase– numerous,e.g.,arraysvs.collections• Keytypes– Target,Adaptee,Adapter• JDK– Arrays.asList(T[])
2215-214
Bridge
• Intent– Decoupleanabstractionfromitsimplementationsotheycanvaryindependently
• Usecase– portablewindowingtoolkit• Keytypes– Abstraction,Implementor• JDK– JDBC,JavaCryptographyExtension(JCE)– BothareServiceProviderInterface(SPI)frameworks– SPIis BridgeImplementor!
2415-214
Composite
• Intent– Composeobjectsintotreestructures.Letclientstreatprimitives&compositionsuniformly.
• Usecase– GUItoolkit(widgetsandcontainers)• Keytype– Componentthatrepresentsbothprimitivesandtheircontainers
• JDK– javax.swing.JComponent
2515-214
CompositeIllustrationpublic interface Expression {
double eval(); // Returns valueString toString(); // Returns infix expression string
}
public class UnaryOperationExpression implements Expression {public UnaryOperationExpression(
UnaryOperator operator, Expression operand);}public class BinaryOperationExpression implements Expression {
public BinaryOperationExpression(BinaryOperator operator,Expression operand1, Expression operand2);
}public class NumberExpression implements Expression {
public NumberExpression(double number);}
2615-214
Decorator
• Intent– attachfeaturestoanobjectdynamically• Usecase– attachingbordersinaGUItoolkit• Keytypes– Component, implementbydecoratoranddecorated
• JDK– Collections(e.g.,Synchronizedwrappers),java.io streams,Swingcomponents
2815-214
Façade
• Intent– Provideasimpleunifiedinterfacetoasetofinterfacesinasubsystem– GoF allowforvariantswherethecomplexunderpinningsareexposedandhidden
• Usecase– anycomplexsystem;GoF usecompiler• Keytypes– Façade(thesimpleunifiedinterface)• JDK– java.util.concurrent.Executors
3015-214
Flyweight
• Intent– usesharingtosupportlargenumbersoffine-grainedobjectsefficiently
• Usecase– charactersinadocument• Keytypes– theFlyweight(instance-controlled!)– Statecanbemadeextrinsic tokeepFlyweightsharable
• JDK– Pervasisve!Allenums,manyothers.j.u.c.TimeUnithas#unitsasextrinsic state.
3215-214
Proxy
• Intent– surrogateforanotherobject• Usecase– delayloadingofimagestillneeded• Keytypes– Subject,Proxy,RealSubject• Gof mentionseveralflavors– virtualproxy– stand-inthatinstantiateslazily– remoteproxy– localrepresentativeforremoteobj– protectionproxy– deniessomeopstosomeusers– smartreference– doeslockingorref.counting,e.g.
• JDK– RMI,collectionswrappers
3315-214
ProxyIllustrationsVirtual Proxy
Smart Reference Remote Proxy
SynchronizedList ArrayList
aTextDocumentimage anImage
data
in memory on disk
anImageProxyfileName
Client
Proxy
Server
3415-214
III.BehavioralPatterns
1. ChainofResponsibility2. Command3. Interpreter4. Iterator5. Mediator6. Memento7. Observer8. State9. Strategy10. Templatemethod11. Visitor
3515-214
ChainofResponsibility
• Intent– avoidcouplingsendertoreceiverbypassingrequestalonguntilsomeonehandlesit
• Usecase– context-sensitivehelpfacility• Keytypes– RequestHandler• JDK– Classloader,Properties• ExceptionhandlingcouldbeconsideredaformofChainofResponsibilitypattern
3615-214
Command
• Intent– encapsulaterequestasobject,lettingyouparameterizeclientswithdifferentactions,queueorlogrequests,etc.
• Usecase– menutree• Keytypes– Command (anexecutemethod)• JDK– Runnable,executorframework• IsitCommandpatternifyourunitmorethanonce?Ifittakesanargument?Returnsaval?
3715-214
Interpreter
• Intent– Givenalanguage,defineclasshierarchyforparsetree,recursivemethodtointerpretit
• Usecase– regularexpressionmatching• Keytypes– Expression,NonterminalExpression,TerminalExpression
• JDK– nousesI’mawareof– Ourexpressionevaluator(HW2)isaclassicexample
• NecessarilyusesCompositepattern!
3815-214
InterpreterIllustrationpublic interface Expression {
double eval(); // Returns valueString toString(); // Returns infix expression string
}
public class UnaryOperationExpression implements Expression {public UnaryOperationExpression(
UnaryOperator operator, Expression operand);}public class BinaryOperationExpression implements Expression {
public BinaryOperationExpression(BinaryOperator operator,Expression operand1, Expression operand2);
}public class NumberExpression implements Expression {
public NumberExpression(double number);}
3915-214
Iterator
• Intent– provideawaytoaccesselementsofacollectionwithoutexposingrepresentation
• Usecase– collections• Keytypes– Iterable,Iterator– ButGoF recognizeinternaliterationtoo
• JDK– Collections,for-eachstatement,etc.
4015-214
Mediator
• Intent– Defineanobjectthatencapsulatehowasetofobjectsinteracttoreducecoupling.– O(n)couplingsinsteadofO(n!)=O(2n)
• Usecase– dialogboxwherechangeinonecomponentaffectsbehaviorofothers
• Keytypes– Mediator,components• JDK– Unclear
4215-214
Memento
• Intent– Withoutviolatingencapsulation,allowclienttocaptureanobject’sstate,andrestore
• Usecase– undostackforoperationsthataren’teasilyundone,e.g.,line-arteditor
• Keytype– Memento(opaquestateobject)• JDK– nonethatI’mawareof(not serialization)
4315-214
Observer
• Intent– Letobjectsobservethebehaviorofotherobjectssotheycanstayinsync
• Usecase– multipleviewsofadataobjectinaGUI• Keytypes– Subject (“observable”),Observer– GoF areagnosticonmanydetails!
• JDK– Swing,leftandright
4415-214
State
• Intent– useanobjectinternallytorepresentthestateofanotherobject;delegatemethodinvocationstothestateobject
• Usecase– TCPConnection(whichisstateful)• Keytype– State• JDK– nonethatI’mawareofbut–Worksgreat inJava– Useenums asstates– UseAtomicReference<State> tostoreit
4515-214
Strategy
• Intent– representabehaviorthatparameterizesanalgorithmforbehaviororperformance
• Usecase– line-breakingfortextcompositing• Keytypes– Strategy• JDK– Comparator
4615-214
Templatemethod
• Intent– defineskeletonofanalgorithmordatastructure,deferringsomedecisionstosubclasses
• Usecase– applicationframeworkthatletspluginsimplementalloperationsondocuments
• Keytypes– AbstractClass,ConcreteClass• JDK– Skeletalcollectionimpls (e.g.,AbstractList)• Note– templatemethodisdualtostrategy,youcanmechanicallyconvertonetotheother
4715-214
TemplateMethodIllustration// List adapter for primitive int arrayspublic static List<Integer> intArrayList(final int[] a) {
return new AbstractList<Integer>() {public Integer get(int i) {
return a[i];}
public Integer set(int i, Integer val) {Integer oldVal = a[i];a[i] = val;return oldVal;
}
public int size() {return a.length;
}};
}
4815-214
Visitor
• Intent– Representanoperationtobeperformedonelementsofanobjectstructure(e.g.,aparsetree).Visitorletsyoudefineanewoperationwithoutmodifyingthetypehierarchy.
• Usecase– type-checking,pretty-printing,etc.• Keytypes– Visitor,ConcreteVisitor,allthetypesthatgetvisited
• JDK– NonethatI’mawareof
4915-214
MoreonVisitor
• VisitorisNOTmerelytraversingagraphstructureandapplyingamethod– That’sIterator
• Theessenceofvisitorisdouble-dispatch– FirstdynamicallydispatchontheVisitor– Thenontheobjectbeingvisited