Design Patterns CSC 335 ObjectOriented Programming and Design Outline Overview of Design Patterns Two Design Patterns Iterator one you have used Strategy from Heads First Chapter 1 The Beginning of Patterns ID: 361820
Download Presentation The PPT/PDF document "Object-Oriented" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Object-Oriented Design Patterns
CSC 335: Object-Oriented
Programming and DesignSlide2
OutlineOverview of Design PatternsTwo Design PatternsIterator, one you have usedStrategy, from Heads First Chapter 1Slide3
The Beginning of PatternsChristopher Alexander, architectA Pattern Language--Towns, Buildings, ConstructionTimeless Way of Building (1979)“Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.”Other patterns: novels (tragic, romantic, crime), movies genres (drama, comedy, documentary) Slide4
“Gang of Four” (GoF) BookDesign Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley Publishing Company, 1994Written by this "gang of four"Dr. Erich Gamma, then Software Engineer, Taligent, Inc.Dr. Richard Helm, then Senior Technology Consultant, DMR GroupDr. Ralph Johnson, then and now at University of Illinois, Computer Science DepartmentDr. John Vlissides, then a researcher at IBM Thomas J. Watson Research Center See John's WikiWiki tribute page http://c2.com/cgi/wiki?JohnVlissidesSlide5
Object-Oriented Design PatternsThis book defined 23 patterns in three categoriesCreational patterns deal with the process of object creationStructural patterns, deal primarily with the static composition and structure of classes and objectsBehavioral patterns, which deal primarily with dynamic interaction among classes and objectsSlide6
Documenting Discovered PatternsMany other patterns have been introduced documentedFor example, the book Data Access Patterns by Clifton Nock introduces 4 decoupling patterns, 5 resource patterns, 5 I/O patterns, 7 cache patterns, and 4 concurrency patterns.Other pattern languages include telecommunications patterns, pedagogical patterns, analysis patternsPatterns are mined at places like Patterns ConferencesSlide7
ChiliPLoPA few patterns work-shopped at ChiliPLoP, Wickenburg and Carefree Arizona (books now)Patterns of Enterprise Application Architecture Martin FowlerPatterns of Fault Tolerant Software, Bob HamnerPatterns of Adopting Agile Development Practices Amr Elssamadisy2010: Patterns of Parallel Programming, Ralph Johnson16 patterns and one Pattern LanguageSlide8
GoF PatternsCreational PatternsAbstract Factory Builder Factory Method Prototype Singleton Structural PatternsAdapter BridgeComposite Decorator FaçadeFlyweight ProxyBehavioral Patterns
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
VisitorSlide9
Why Study Patterns?Reuse tried, proven solutionsProvides a head startAvoids gotchas later (unanticipated things)No need to reinvent the wheelEstablish common terminologyDesign patterns provide a common point of referenceEasier to say, “We could use Strategy here.”Provide a higher level prospectiveFrees us from dealing with the details too earlySlide10
Other advantagesMost design patterns make software more modifiable, less brittlewe are using time tested solutionsUsing design patterns makes software systems easier to change—more maintainableHelps increase the understanding of basic object-oriented design principlesencapsulation, inheritance, interfaces, polymorphismSlide11
Style for Describing PatternsWe will use this structure to describe them:Pattern nameRecurring problem: what problem the pattern addressesSolution: the general approach of the patternUnified Modeling Language (UML) view of the patternParticipants: a description as a class diagramUsages: examples of this patternSlide12
A few OO Design PatternsComing up:Iteratoraccess the elements of an aggregate object sequentially without exposing its underlying representationStrategy A means to define a family of algorithms, encapsulate each one as an object, and make them interchangeableSlide13
IteratorSlide14
Pattern: IteratorName: Iterator (a.k.a Enumeration)Recurring Problem: How can you loop over all objects in any collection. You don’t want to change client code when the collection changes. Want the same methodsSolution: 1) Have each class implement an interface, and 2) Have an interface that works with all collectionsConsequences: Can change collection class details without changing code to traverse the collectionSlide15
GoF Version of Iterator page 257ListIteratorFirst()Next()
IsDone()
CurrentItem()
// A C++ Implementation
ListIterator<Employee> itr = list.iterator();
for(itr.First(); !itr.IsDone(); itr.Next()) {
cout << itr.CurrentItem().toString();Slide16
Java’s version of Iterator public interface Iterator<E> { boolean hasNext(); E next(); void
remove();
//optional
}
hasNext
returns
true if the iteration has more
elements
next
returns
the next element in the
iteration
remove
removes
the last element that was returned by
next
from the underlying
Collection, call only once per
next
Slide17
Java’s Iterator interface // The Client code List<BankAccount> bank = new ArrayList<BankAccount>(); bank.add(new BankAccount(""First", 0.01) );
// ...
bank.add
(new BankAccount
("Last"
, 9000.00));
String ID =
"Last"
;
Iterator
<BankAccount>
itr
=
bank.
iterator
();
while(
itr
.hasNext
()
) {
if
(
itr
.next
()
.
getID
().equals(
searchAcct.getID
()))
System.out.println
("Balance
" +
getBalance
(
));
} Slide18
UML Diagram of Java's Iterator with a few Collections<<interface>>Iterator
hasNext()
next()
<<
interface
>>
List
iterator(): Iterator
…
Client
Vector
iterator(
)
Iterator
hasNext()
next()
LinkedList
iterator()
ArrayList
iterator()
http://download.oracle.com/javase/8/docs/api/java/util/List.htmlSlide19
Strategy Design PatternStrategySlide20
Pattern: StrategyName: Strategy (a.k.a Policy)Problem: You want to encapsulate a family of algorithms and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it (GoF)Solution: Create an abstract strategy class (or interface) and extend (or implement) it in numerous ways. Each subclass defines the same method names in different waysSlide21
General Form with extendshttp://www.dofactory.com/net/strategy-design-patternSlide22
Example Usage with implementshttp://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorialSlide23
Design Pattern: StrategyConsequences: Allows families of algorithms Known uses from the Gang of 4 book:ET++ and Interviews use different line breaking strategiesRTL System for compiler code optimization, strategies defining different register allocation schemes and instruction set scheduling policiesSwapsManager calculation engine framework computes prices for different financial instrumentsRApp use strategies to lay out route wires to connect subsytems on the circuits Rapp producesSlide24
Design Pattern: StrategySaving files in different formats, Word, ODT, RTF, HTML plain text.Compress files using different compression algorithms.Capture video using different video compression algorithms.Plot the same data using different formats (points, line chart, bar chart, etc.)Display calendars, with different holidays for different countries (Strategy classes are USAHoliday, CanadaHoliday…A store may have various pricing strategies (10% off everything, $10 off when the total exceeds $200, etc.), and these strategies may be used at different times.Slide25
Design Pattern: StrategyKnown uses more locallyLayout managers in JavaDifferent Poker Strategies in a 335 ProjectDifferent PacMan ghost chasing strategies in a 335 ProjectDifferent Strategies for taking over the world in a 335 ProjectSlide26
Code DemoPlay tic tac toe against two different AIs