Title: Presentation 13 modified from Tuesday
1CSC 335 Object-Oriented Programming and Design
Presentation 13 (modified from
Tuesday Object-Oriented Design Patterns
2Patterns A definition
- A pattern is a solution to a problem in a context
- 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.
3OOPSLA 96 Alexander PicDoug Lea quote
- "Alexander's central premise, driving over thirty
years of thoughts, actions, and writings, is
that there is something fundamentally wrong with
twentieth century architectural design methods
and practices. ... Alexander illustrates failures
in the sensitivity of contemporary methods to the
actual requirements and conditions surrounding
their development. He argues that contemporary
methods fail to generate products that satisfy
the true requirements placed upon them by
individuals and society, and fail to meet the
real demands of real users, and ultimately fail
in the basic requirement that design and
engineering improve the human condition."
4Alexander"Quality without a name" Quote from
Dick Gabriel (Sun Fellow)
- "Its modules and abstractions are not too big. If
they were too big, their size and inflexibility
would have created forces that would overgovern
the overall structure of the software every
module, function, class, and abstraction is small
and named so that I know what it is without
looking at its implementation. - If I look at any small part of it, I can see what
is going on, I don't need to refer to other parts
to understand what something is doing. This tells
me that the abstractions make sense for
themselves -- they are whole. - If I look at any large part in overview, I can
see what is going on, I don't need to know all
the details to get it. - Everything about it seems familiar.
- I can imagine changing it, adding some
functionality. - I am not afraid of it, I will remember it."
5Patterns in the GoF book
- The Gang of Four did not invent the patterns
- They found patterns that already existed in the
software community 23 from book liner are
attached - These are the similarities found in the design of
software viewed to be of high quality - They made a rule to list three different systems
that solved a problem in the same manner - Thousands of patterns have been documented since
- telecommunications patterns, pedagogical
patterns, analysis patterns, indexing patterns
6What a pattern has
- Formats of pattern writers vary, but a pattern
usually has at least these four things - A name (Iterator, Stategy, Observer, Composite)
- The purpose of the pattern, the problem it solves
- A guide for how to accomplish the solution
- The constraints and forces to be considered in
order to accomplish the solution
7Why Study Patterns?
- Can reuse solutions
- gives us a head start
- avoids the gotchas later (unanticipated things)
- no need to reinvent the wheel
- Establish common terminology
- Design patterns provide a common point of
reference - Easier to say, "We need some Strategies here"
- Provide a higher level prospective
- frees us from dealing with the details too early
8Carpenter's ConversationAdapted from Ralph
Johnson
- How should we build the cabinet drawers?
- Cut straight down into the wood, cut back up 45
degrees a specific length, then go straight back
down a specific length, the cut back up at 45
degrees until you reach, .....
9A Higher Level Discussion
- A high level discussion could have been
- "Should we use a miter joint or a dovetail
joint?" - This is a higher, more abstract level
- Avoids getting bogged down in details
- Which level of detail is more efficient?
10Consequences of which joint
- Dovetail joints
- are more complex, more expensive to make
- withstands climate conditions dovetail joint
remains solid as wood contracts and expands - independent of fastening system
- more pleasing to look at
- Thoughts underneath this question are
- Should we make a beautiful durable joint or a
cheap and dirty one that lasts until the check
clears?
11Consequences
- Carpenters, patterns writers, and software
developers discuss consequences - consequences simply refer to cause and effect
- If we do this, what will happen both good and
bad - also known as the forces that patterns consider
- Example If we use Mediator to add and drop
courses - Add an extra class that needs reference to
several objects - All of the logic and process is confined to one
class so any change to the "rules" would be
handled there - Reduces dependencies between others objects
(simpler design when student does NOT tell the
scheduled course to change)
12Other advantages
- Most design patterns make software more
modifiable, less brittle - we are using time tested solutions
- Helps increase the understanding of basic
object-oriented design principles - encapsulation, inheritance, interfaces,
polymorphism - Designs of large systems can avoid large
inheritance hierarchies (there are alternatives) - learned the hard way about big inheritance
hierarchies
13A few Patterns
- The next slides present a few patterns
- Iterator Pattern that you have seen in 227 or
127B - Strategy, which you will use in your final
project - Observer is mentioned, you will use this in your
final project
14Pattern Iterator
- Name Iterator (a.k.a Enumeration)
- Problem How can you loop over all objects in any
collection. You dont want to change client code
when the collection changes. You also want the
same interface (methods) - Solutions 1) Have each of your classes implement
an interface. 2) Have an Iterator interface that
works with all collections - Consequences Can change collection class without
changing code to traverse the collection
15One Java version of an Iterator
- interface Enumeration
- boolean hasMoreElements()
- Tests if this enumeration contains more elements.
- Object nextElement()
- Returns the next element of this enumeration if
this enumeration object has at least one more
element to provide.
16Another Java version of an Iterator
- interface Iterator
- boolean hasNext()
- Returns true if the iteration has more elements.
- Object next()
- Returns the next element in the iteration
17Could change to ArrayList to LinkedList
- // The Client code
- List bank new ArrayList( )
- bank.add( new BankAccount("one", 0.01 ) )
- // ...
- bank.add(new BankAccount("nine thousand",
9000.00) ) - String ID ???
- BankAccount searchAcct new BankAccount( ID,
0.00 ) - Iterator i bank.iterator( )
- while( i.hasNext( ) )
-
- BankAccount ref (BankAccount)i.next( )
- if( ref.compareTo( searchAcct ) 0 )
- System.out.println( "Found " ref.getID()
) -
18UML Diagram of Java's Iterator and Collections
ltltinterfacegtgt List iterator()
ltltinterfacegtgt Iterator hasNext() next()
Vector iterator()
LinkedList iterator()
ArrayList iterator()
Iterator hasNext() next()
Context
19Pattern Strategy
- Name Strategy (a.k.a Policy)
- Problem You want to encapsulate a family of
algorithms and make them interchangeable.
Strategy lets the 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 ways
20Pattern Strategy
- Consequences
- Allows families of algorithms. Known uses
- Layout managers in Java
- Different Poker Strategies in 335 Project Fall
2000 - Different Pakman chase strategies 335 Fall 2001
- TextField validators in dBase and Borland OWL
- Will use different algorithms to verify if the
user input is a valid integer, double, string,
date, yes/no. - Eliminates conditional statements
- Don't need to keep asking, if this is supposed to
be an int do this, else if it is a string do that
21Java Example of Strategy
- this.setLayout( new FlowLayout( ) )
- this.setLayout( new GridLayout( ) )
- In Java, a container contains a layout manager
- There is a default perhaps set in the
constructor - You can change a container's layout manager with
a setLayout message - Could use same approach in Ghosts
- Ghosts have common methods but could change an
instance variable at runtime with - setStrategy( new RandomStategy( ) )
22interface LayoutManager
- Java has a java.awt.LayoutManager interface
- Known Implementing Classes
- GridLayout, FlowLayout, ScrollPaneLayout
- Each class implements the following methods
- addLayoutComponent(String name, Component comp)
- layoutContainer(Container parent)
- minimumLayoutSize(Container parent)
- preferredLayoutSize(Container parent)
- removeLayoutComponent(Component comp)
23General UML Diagram of Strategy
ltltinterfacegtgt Strategy AlgorithmInterface
Context strategy Strategy ContextInterface
implements
ConcreteClassA AlgorithmInterface
ConcreteClassB AlgorithmInterface
ConcreteClassC AlgorithmInterface
24Specific UML Diagram of LayoutManager
ltltinterfacegtgt LayoutManager addLayoutComponent() l
ayoutContainer() minimumLayoutSize()
JPanel panel Panel size Dimension setLayout(lm
LayoutManager) setPreferredSize(diDimension)
implements
GridLayout addLayoutComponent() layoutContainer()
minimumLayoutSize()
FlowLayout addLayoutComponent() layoutContainer()
minimumLayoutSize()
ScrollPaneLayout addLayoutComponent() layoutContai
ner() minimumLayoutSize()
25Change the stategy at runtime
- Demonstrate LayoutControllerFrame.java
- Source code online and attached
- private class FlowListener implements
ActionListener - // There is another ActionListener for
GridLayout - public void actionPerformed( ActionEvent evt )
- // Change the layout strategy of the JPanel
- // and tell it to lay itself out
- centerPanel.setLayout( new FlowLayout( ) )
- centerPanel.validate( )
-
-
26Strategy in a familiar game
- Imagine a card game (BlackJack) that has a human
player that requires human interaction and some
computer players to keep you company as you loose
money - We want accomplices with varied skills that can
change at runtime - First an interface
- public interface DrawCardStrategy
- // Need dealer in most strategies
- public boolean wantAnotherCard(Dealer
theDealer)
27One Strategy
- public class NaiveStrategy implements
DrawCardStrategy -
- private static Random generator new Random(
) - public boolean wantAnotherCard(Dealer
theDealer) - // Do not need parameter for NaivePlayers
- // However, Other strategies will use the
dealer - if(generator.nextInt(2) 0)
- return true
- else
- return false
-
28 A Second Strategy
- public class IntermediateStategy implements
DrawCardStrategy -
- // Get another card when the dealer shows 7 or
more - public boolean wantAnotherCard(Dealer
theDealer) -
- return theDealer.showingCards().pointValue()
gt 7 -
29Add a third or fourth ...
- public class ExpertStategy implements
DrawCardStrategy -
- // Draw cards based on card counting
- public boolean wantAnotherCard(Dealer
theDealer) -
- // TBA ... complex algorithm
-
-
30Used in the Player Class
- public class Player
-
- private String myName
- private DrawCardStrategy myStrategy
- public Player(String name)
-
- myName name
- // Default Strategy
- myStrategy new NaiveStrategy()
-
- // This is the contextInterface
- public void setDrawCardStrategy(DrawCardStrategy
aStrategy) -
- myStrategy aStrategy
-
- // The GameModel needs to ask this question
often
31Specific UML Diagram of DrawCardStrategy
ltltinterfacegtgt DrawCardStrategy wantAnotherCard(d
ealerDealer) Boolean
Player currentStrategy DrawCardStrategy setStrate
gy(dsDrawCardStrategy)
implements
NaiveStrategy wantAnotherCard(dealerDealer)
Boolean
SmartStrategy wantAnotherCard(dealerDealer)
Boolean
32Observer
- Observer Define a 1 to many relationship so when
one object changes state, all dependents are
notified and they update the view themselves. - You will be able to switch views at runtime or to
show 2 or more views at the same time - Java supports this with Observer/Observable
- More in this later
33Examples of Observer
- Example of the Observer Pattern you see often
- Show 3 Explorer windows with 3 different views
- Delete a file in one of the windows
- Show Spreadsheet
- Data is the model
- Charts are the view
34UML Diagram of Observer
35OOP and UI
- Decoupled UIs
- One model may have several user interfaces
- Web, phone, PDA, GUI on a desktop
- Each UI will hook into the same model
- But allow IO in different ways
- Desired change UI without changing the model
- Desired change the model without changing the UI
- Do not imbed the UI code inside the model
- Keep the two separate
36Not good design
- See pages 307-309 for a JPanel that also
maintains a bank account balance - there is no bank account, which could be the
"model" - Dice game should have had a Game class that could
be played with a GUI or a text UI - Having the logic in the listener tightly couples
the model with the UI - Here is actual code that was turned in
37- // private PlayListener class called when "roll"
button is - // pressed records values of both the dice and
decides win - private class PlayListener implements
ActionListener -
- public void actionPerformed(ActionEvent e)
-
- Die d new Die()
- int onE d.roll() // records first die
value - int twO d.roll() // records second die
value - int sum onE twO // records the sum of
values - int result
- String str""
- if(sum7sum11) // if player wins
-
- resultWIN
- str"You Win -)"
-
- else//if he loses
38Not decoupled
- The GUI should not have the rules, the game
should - What if the game has 2s and 12s winning?
- public class DieGUI extends JFrame
-
- //class constants for a win
- private static final int WIN1 7
- private static final int WIN2 11
39Much Better Rules in the game (a.k.a) the model
- private class PlayListener implements
ActionListener -
- public void actionPerformed(ActionEvent e)
-
- if(currentPlayer null)
-
- JOptionPane.showMessageDialog(null,
- "Please Enter a Name First")
- return
-
- // play the game and set the output
- resultLabel.setText(""
- currentPlayer.playGame().toString() )
-
-
40The Model keeps history
- // Once the menu item is clicked it will pop up a
new - // Option Dialog with history of the current
player - private class HistoryListener implements
ActionListener -
- public void actionPerformed(ActionEvent e)
-
- String output "History for "
- currentPlayer.getName() "\n\n"
- ArrayList history currentPlayer.getHistory()
- for(int i 0 i lt history.size() i )
- output history.get(i).toString() "\n"
- JOptionPane.showMessageDialog(null, output)
-
-
41MVC
- Model-View-Controller (MVC) you have used this in
you event-driven programs with a GUI and in your
final project