57
1 15-214 School of Computer Science 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour of the Gang-of-Four Design Patterns Josh Bloch Charlie Garrod

23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

115-214

SchoolofComputerScience

23Patternsin80Minutes:aWhirlwindJava-centricTouroftheGang-of-FourDesignPatterns

JoshBloch CharlieGarrod

Page 2: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

215-214

Administrivia

• Homework6checkpointdueFriday5:00pm• FinalexamFriday,Dec16th 5:30–8:30pm,GHC4401– ReviewsessionWednesday,Dec14th 7–9:30pm,DH1112

Page 3: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

315-214

Outline

I. CreationalPatternsII. StructuralPatternsIII. BehavioralPatterns

Page 4: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

415-214

PatternName

• Intent – theaimofthispattern• Usecase– amotivatingexample• Keytypes – thetypesthatdefinepattern– Italictypenameindicatesabstractclass;typicallythisisaninterfacewhenthepatternisusedinJava

• JDK – example(s)ofthispatternintheJDK

Page 5: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

515-214

Illustration

• Codesample,diagram,ordrawing– Timeconstraintsmakeitimpossibletoincludeillustrationsfromsomepatterns

Page 6: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

615-214

I.CreationalPatterns

1. Abstractfactory2. Builder3. Factorymethod4. Prototype5. Singleton

Page 7: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

715-214

1.AbstractFactory

• Intent– allowcreationoffamiliesofrelatedobjectsindependentofimplementation

• Usecase– look-and-feelinaGUItoolkit– EachL&Fhasitsownwindows,scrollbars,etc.

• Keytypes– Factory withmethodstocreateeachfamilymember,Products

• JDK– notcommon

Page 8: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

815-214

AbstractFactoryIllustration

Client

Window

PMWindow MotifWindow

PMScrollBar MotifScrollBar

ScrollBar

WidgetFactoryCreateWindow()CreateScrollBar()

MotifWidgetFactoryCreateWindow()CreateScrollBar()

PMWidgetFactoryCreateWindow()CreateScrollBar()

Page 9: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

915-214

2.Builder

• Intent– separateconstructionofcomplexobjectfromrepresentationso samecreationprocesscancreatedifferentrepresentations

• usecase– convertingrichtexttovariousformats• types– Builder,ConcreteBuilders,Director,Products• JDK– StringBuilder,StringBuffer*– Butthereisno(visible)abstractsupertype…– Andbothgeneratesameproductclass(String)

Page 10: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1015-214

Gof4BuilderIllustrationRTFReaderParseRTF()

while(t=nextToken){switchtType{CHAR:builder->AddChar(t.Char)FONT:builder->SetFont(t.Font)PARA:builder->AddParagraph()

}}

TextConverterAddChar(char)SetFont(font)AddParagraph()

ASCIIConverterAddChar(char)GetASCIIText()

TeXConverter

AddChar(char)SetFont(font)AddParagraph()GetTeXText()

GUITextConverter

AddChar(char)SetFont(font)AddParagraph()GetGUIText()

Builders

GUITextTeXTextASCIIText

Page 11: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1115-214

MytakeonBuilder[EJItem1]

• Emulatesnamedparametersinlanguagesthatdon’tsupportthem

• Emulates2n constructorsorfactorieswithnbuildermethods,byallowingthemtobecombinedfreely

• Costisanintermediate(Builder)object

Page 12: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1215-214

EJ-styleBuilderIllustrationNutritionFacts 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) { ... }

}

Page 13: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1315-214

3.FactoryMethod

• Intent– abstractcreationalmethodthatletssubclassesdecidewhichclasstoinstantiate

• Usecase– creatingdocumentsinaframework• Keytypes– Creator,whichcontainsabstractmethodtocreateaninstance

• JDK– Iterable.iterator()• RelatedStaticFactorypatternisverycommon– TechnicallynotaGoF pattern,butcloseenough

Page 14: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

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() { ... }...

}

Collection<String> c = ...;

for (String s : c) // Creates an Iterator appropriate to cSystem.out.println(s);

Page 15: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1515-214

4.Prototype

• Intent– createanobjectbycloninganotherandtweakingasnecessary

• Usecase– writingamusicscoreeditorinagraphicaleditorframework

• Keytypes– Prototype• JDK– Cloneable,butavoid(exceptonarrays)– JavaandPrototypepatternareapoorfit

Page 16: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1615-214

5.Singleton

• Intent– ensuringaclasshasonlyoneinstance• Usecase– GoF sayprintqueue,filesystem,companyinanaccountingsystem– Compellingusesarerarebuttheydoexist

• Keytypes– Singleton• JDK– java.lang.Runtime

Page 17: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1715-214

SingletonIllustrationpublic enum Elvis {

ELVIS;

sing(Song song) { ... }

playGuitar(Riff riff) { ... }

eat(Food food) { ... }

take(Drug drug) { ... }}

// Alternative implementationpublic class Elvis {

public static final Elvis ELVIS = new Elvis();private Elvis() { }...

}

Page 18: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1815-214

MytakeonSingleton

• It’saninstance-controlledclass;othersinclude– Staticutilityclass– non-instantiable– Enum – oneinstancepervalue,allvaluesknownatcompiletime

– Internedclass– onecanonicalinstancepervalue,newvaluescreatedatruntime

• Thereisadualitybetweensingletonandstaticutilityclass

Page 19: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

1915-214

II.StructuralPatterns

1. Adapter2. Bridge3. Composite4. Decorator5. Façade6. Flyweight7. Proxy

Page 20: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2015-214

1.Adapter

• Intent– convertinterfaceofaclassintoonethatanotherclassrequires,allowinginteroperability

• Usecase– numerous,e.g.,arraysvs.collections• Keytypes– Target,Adaptee,Adapter• JDK– Arrays.asList(T[])

Page 21: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2115-214

AdapterIllustration

Havethisandthis?Usethis!

Page 22: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2215-214

2.Bridge

• Intent– decoupleanabstractionfromitsimplementationsotheycanvaryindependently

• Usecase– portablewindowingtoolkit• Keytypes– Abstraction,Implementor• JDK– JDBC,JavaCryptographyExtension(JCE),JavaNaming&DirectoryInterface(JNDI)

• Bridgepatternvery similartoServiceProvider– Abstraction~API,Implementer ~SPI

Page 23: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2315-214

BridgeIllustration

Page 24: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2415-214

3.Composite

• Intent– composeobjectsintotreestructures.Letclientstreatprimitives&compositionsuniformly.

• Usecase– GUItoolkit(widgetsandcontainers)• Keytype– Componentthatrepresentsbothprimitivesandtheircontainers

• JDK– javax.swing.JComponent

Page 25: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

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);}

Page 26: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2615-214

4.Decorator

• Intent– attachfeaturestoanobjectdynamically• Usecase– attachingbordersinaGUItoolkit• Keytypes– Component,implementbydecoratorand decorated

• JDK– Collections(e.g.,Synchronizedwrappers),java.io streams,Swingcomponents

Page 27: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2715-214

DecoratorIllustration

Page 28: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2815-214

5.Façade

• Intent– provideasimpleunifiedinterfacetoasetofinterfacesinasubsystem– GoF allowforvariantswherethecomplexunderpinningsareexposedandhidden

• Usecase– anycomplexsystem;GoF usecompiler• Keytypes– Façade(thesimpleunifiedinterface)• JDK– java.util.concurrent.Executors

Page 29: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

2915-214

FaçadeIllustration

Façade

√√

√ √

Subsystem classes

Page 30: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3015-214

6.Flyweight

• Intent– usesharingtosupportlargenumbersoffine-grainedobjectsefficiently

• Usecase– charactersinadocument• Keytypes– Flyweight(instance-controlled!)– Somestatecanbeextrinsic toreducenumberofinstances

• JDK– Common!Allenums,manyothers– j.u.c.TimeUnit hasnumberofunitsasextrinsicstate

Page 31: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3115-214

FlyweightIllustration

Page 32: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3215-214

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

Page 33: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3315-214

ProxyIllustrationsVirtual Proxy

Smart Reference Remote Proxy

SynchronizedList ArrayList

aTextDocumentimage anImage

data

in memory on disk

anImageProxyfileName

Client

Proxy

Server

Page 34: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3415-214

III.BehavioralPatterns

1. ChainofResponsibility2. Command3. Interpreter4. Iterator5. Mediator6. Memento7. Observer8. State9. Strategy10. Templatemethod11. Visitor

Page 35: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3515-214

1.ChainofResponsibility

• Intent– avoidcouplingsendertoreceiverbypassingrequestalonguntilsomeonehandlesit

• Usecase– context-sensitivehelpfacility• Keytypes– RequestHandler• JDK– ClassLoader,Properties• ExceptionhandlingcouldbeconsideredaformofChainofResponsibilitypattern

Page 36: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3615-214

2.Command

• Intent– encapsulatearequestasasanobject,lettingyouparameterizeoneactionwithanother,queueorlogrequests,etc.

• Usecase– menutree• Keytype– Command (Runnable)• JDK– Common!Executorframework,etc.• IsitCommandpatternifyourunitrepeatedly?Ifittakesanargument?Returnsaval?

Page 37: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3715-214

CommandIllustrationpublic static void main(String[] args) {

SwingUtilities.invokeLater(() -> new Demo().setVisible(true)); }

Page 38: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3815-214

3.Interpreter

• Intent– givenalanguage,defineclasshierarchyforparsetree,recursivemethodtointerpretit

• Usecase– regularexpressionmatching• Keytypes– Expression,NonterminalExpression,TerminalExpression

• JDK– nousesI’mawareof– Ourexpressionevaluator(HW2)isaclassicexample

• NecessarilyusesCompositepattern!

Page 39: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

3915-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);}

Page 40: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4015-214

4.Iterator

• Intent– provideawaytoaccesselementsofacollectionwithoutexposingrepresentation

• Usecase– collections• Keytypes– Iterable,Iterator– ButGoF discussinternaliteration,too

• JDK– collections,for-eachstatement,etc.

Page 41: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4115-214

IteratorIllustrationpublic 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() { ... }...

}

Collection<String> c = ...;

for (String s : c) // Creates an Iterator appropriate to cSystem.out.println(s);

Page 42: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4215-214

5.Mediator

• Intent– defineanobjectthatencapsulateshowasetofobjectsinteract,toreducecoupling.– 𝓞(n)couplingsinsteadof𝓞(n2)

• Usecase– dialogboxwherechangeinonecomponentaffectsbehaviorofothers

• Keytypes– Mediator,Components• JDK– Unclear

Page 43: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4315-214

MediatorIllustration

Page 44: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4415-214

6.Memento

• Intent– withoutviolatingencapsulation,allowclienttocaptureanobject’sstate,andrestore

• Usecase– undostackforoperationsthataren’teasilyundone,e.g.,line-arteditor

• Keytype– Memento(opaquestateobject)• JDK– nonethatI’mawareof(not serialization)

Page 45: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4515-214

7.Observer

• Intent– letobjectsobservethebehaviorofotherobjectssotheycanstayinsync

• Usecase– multipleviewsofadataobjectinaGUI• Keytypes– Subject (“Observable”),Observer– GoF areagnosticonmanydetails!

• JDK– Swing,leftandright

Page 46: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4615-214

ObserverIllustration// Implement roll button and dice type fieldJTextField diceSpecField = new JTextField(diceSpec, 5); // Field widthJButton rollButton = new JButton("Roll");rollButton.addActionListener(event -> {if (!diceSpecField.getText().equals(diceSpec)) {

diceSpec = diceSpecField.getText();dice = Die.dice(diceSpec);jDice.resetDice(dice);

}for (Die d : dice) d.roll();jDice.repaint();

});

Page 47: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4715-214

8.State

• Intent– allowanobjecttoalteritsbehaviorwheninternalstatechanges.“Objectwillappeartochangeclass.”

• Usecase– TCPConnection(whichisstateful)• Keytype– State(Objectdelegatestostate!)• JDK– nonethatI’mawareof,but…–Worksgreat inJava– Useenums asstates– UseAtomicReference<State> tostoreit

Page 48: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4815-214

9.Strategy

• Intent– representabehaviorthatparameterizesanalgorithmforbehaviororperformance

• Usecase– line-breakingfortextcompositing• Keytypes– Strategy• JDK– Comparator

Page 49: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

4915-214

StrategyIllustrationComparator isastrategyfororderingpublic static synchronized void main(String[] args) {

Arrays.sort(args, Comparator.reverseOrder());System.out.println(Arrays.toString(args));

Arrays.sort(args, Comparator.comparingInt(String::length));System.out.println(Arrays.toString(args));

}

java Foo i eat wondrous spam[wondrous, spam, i, eat][i, eat, spam, wondrous]

Page 50: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5015-214

10.TemplateMethod

• Intent– defineskeletonofanalgorithmordatastructure,deferringsomedecisionstosubclasses

• Usecase– applicationframeworkthatletspluginsimplementalloperationsondocuments

• Keytypes– AbstractClass,ConcreteClass• JDK– skeletalcollectionimpls (e.g.,AbstractList)

Page 51: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5115-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;

}};

}

Page 52: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5215-214

11.Visitor

• Intent– representanoperationtobeperformedonelementsofanobjectstructure(e.g.,aparsetree).Visitorletsyoudefineanewoperationwithoutmodifyingthetypehierarchy.

• Usecase– type-checking,pretty-printing,etc.• Keytypes– Visitor,ConcreteVisitors,alltheelementtypesthatgetvisited

• JDK– nonethatI’mawareof

Page 53: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5315-214

VisitorIllustration(1/3)public interface Expression {

public <T> T accept(Visitor<T> v); // No eval or toString! }

public class UnaryOperationExpression implements Expression {public UnaryOperationExpression(

UnaryOperator operator, Expression operand);public <T> T accept(Visitor<T> v) { return v.visitUnaryExpr(this); }

}public class BinaryOperationExpression implements Expression {

public BinaryOperationExpression(BinaryOperator operator,Expression operand1, Expression operand2);

public <T> T accept(Visitor<T> v) { return v.visitBinaryExpr(this) ; }}public class NumberExpression implements Expression {

public NumberExpression(double number);public <T> T accept(Visitor<T> v) { return v.visitNumberExpr(this); }

}

Page 54: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5415-214

VisitorIllustration(2/3)public interface Visitor<T> { // T is result type

public T visitUnaryExpr(UnaryExpression ue);public T visitBinaryExpr(BinaryExpression be);public T visitNumberExpr(NumberExpression ne);

}

public class EvalVisitor implements Visitor<Double> {public Double visitUnaryExpr(UnaryExpression ue) {

return ue.operator.apply(ue.operand.accept(this));}public Double visitBinaryExpr(BinaryExpression be) {

return be.operator.apply(be.operand1.accept(this),be.operand2.accept(this));

}public Double visitNumberExpr(NumberExpression ne) { return ne.number; }

}

Page 55: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5515-214

VisitorIllustration(3/3)public class ToStringVisitor implements Visitor<String> {

public String visitUnaryExpr(UnaryExpression ue) {return ue.operator + ue.operand.accept(this);

}public String visitBinaryExpr(BinaryExpression be) {

return String.format("(%s %s %s)", be.operand1.accept(this),be.operator, be.operand2.accept(this));

}public String visitNumberExpr(NumberExpression ne) {

return Double.toString(ne.number);}

}

// Sample use of visitorsSystem.out.println(e.accept(new ToStringVisitor()) + " = " +

e.accept(new EvalVisitor()));

Page 56: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5615-214

MoreonVisitor

• VisitorisNOTmerelytraversingagraphstructureandapplyingamethod– That’sIterator!

• Theessenceofvisitorisdouble-dispatch– FirstdynamicallydispatchontheVisitor– Thenontheelementbeingvisited

Page 57: 23 Patterns in 80 Minutes: a Whirlwind Java- centric Tour ...charlie/courses/15-214/2016... · Prototype 5. Singleton. 15-214 7 1. Abstract Factory ... My take on Singleton ... Adapter

5715-214

Summary

• Nowyouknowall theGangofFourpatterns• Definitionscanbevague• Coverageisincomplete• Butthey’reextremelyvaluable– Theygaveusavocabulary– Andawayofthinkingaboutsoftware

• Lookforpatternsasyoureadandwritesoftware– GoF,non-GoF,andundiscovered