More ObjectOriented Design Patterns - PowerPoint PPT Presentation

1 / 41
About This Presentation
Title:

More ObjectOriented Design Patterns

Description:

What is present in good quality design that is not present in a poor quality design? ... 'Its modules and abstractions are not too big. ... Strategy in a familiar game ... – PowerPoint PPT presentation

Number of Views:73
Avg rating:3.0/5.0
Slides: 42
Provided by: rickm1
Category:

less

Transcript and Presenter's Notes

Title: More ObjectOriented Design Patterns


1
CSC 335 Object-Oriented Programming and Design
Presentation 13 More Object-Oriented Design
Patterns
2
Design Patterns
  • 30 years ago, Christopher Alexander asked
  • Are beauty and quality objective?
  • Can we agree some things are beautiful and some
    are not?

3
What is good design?
  • Alexander is an architect (at UC Berkeley today)
  • What makes a good architectural design?
  • What makes bad architectural design?
  • Can we recognize good design?
  • Is there an objective basis for such a judgment?
  • Is there a basis for describing common consensus
  • Alexander believed that beauty can be described
    through an objective basis that can be measured.

4
Cultural Anthropology
  • Within a culture, individuals agree what is good
    design, what is beautiful
  • There are patterns in cultures that serve as
    objective bases for judging design
  • Proposed The quality of software can be measured
    objectively
  • This is the idea behind design patterns
  • Patterns are not invented, they are recognized as
    elegant solutions that have been used many times

5
Two questions
  • Alexander asks
  • What is present in good quality design that is
    not present in a poor quality design?
  • What is present in poor quality design that is
    not present in a good quality design?
  • The task is to identify the things what makes a
    design good and what makes a design bad
  • What are the commonalities in what is viewed as
    good (and what is viewed as bad)

6
Look for commonalities
  • What are the commonalities in what is viewed as
    good and what is viewed as bad
  • A software system that is relatively easy to
    maintain is considered good
  • A fragile software system is considered bad
  • A software system that is easy to understand is
    considered good
  • obfuscated spaghetti code is bad

7
Architecture
  • Alexander observed many buildings, towns,
    streets, gardens, and pieces of furniture
  • Good constructs had things in common
  • They can be different but still of high quality
  • They may solve different problems
  • Consider a porch
  • A porch may be used to provide shade on a hot
    sunny day
  • Another porch provides a transition from the
    outside to the inside and from the inside to the
    outside
  • Did you ever live where there was no roof over
    the door?

8
Can solve the same problem in different ways
  • Or two different porches might solve the same
    problem in two different ways
  • Both may provide a pleasing way to enter or exit
    a house and still look different
  • Alexander was trying to identify and describe the
    consistency of quality in design
  • having a transition from room to room or from
    inside to outside is important
  • those transitions can take many forms

9
Patterns A definition
  • He looked at different structures that solved the
    same problem
  • Found similarities between designs of high
    quality
  • Alexander called these similarities patterns
  • 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.

10
OOPSLA 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."

11
Alexander's Request
  • Alexander believes
  • architects failed (our living spaces are
    filled--too late)
  • the ubiquitous computer and the software that
    runs on it may be another chance to improve the
    quality of life
  • At OOPSLA 1996, Alexander asked the audience of
    2,800 software engineers to take up the challenge
    of making software beautiful. He talked of
    wholeness and living structure
  • Received with a rare standing ovation

12
Alexander"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."

13
Does this relate to Software?
  • Early 1990s software developers wondered if the
    same approach could be used in our discipline
  • Are there problems that occur over and over again
    that could be solved in somewhat the same way?
  • Could software be developed in terms of patterns,
    writing solutions after the pattern was
    identified?
  • People started looking for patterns
  • Then came one of the biggest selling books in
    CS...

14
Gang of Four The GoF Book
  • The book with the greatest influence is
  • Design Patterns Elements of Reusable
    Object-Oriented Software
  • Gamma (who wrote JUnit with Kent Beck), Helm,
    Johnson, and Vlissides
  • This book catalogs 23 patterns (some you have had
    some exposure to)
  • They offer advice for developing quality software

15
Patterns 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

16
What 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

17
Why 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

18
Carpenter'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, .....

19
A 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?

20
Consequences 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?

21
Consequences
  • 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)

22
Other 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

23
A Pattern
  • One pattern you may have seen from 227 or 127B is
    the Iterator Pattern

24
Pattern 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

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

26
Another 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

27
Could 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()
    )

28
UML Diagram of Java's Iterator and Collections
ltltinterfacegtgt List iterator()
ltltinterfacegtgt Iterator hasNext() next()
Vector iterator()
LinkedList iterator()
ArrayList iterator()
Iterator hasNext() next()
Context
29
Pattern 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

30
Pattern 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

31
Java 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( ) )

32
interface 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)

33
General UML Diagram of Strategy
ltltinterfacegtgt Strategy AlgorithmInterface
Context strategy Strategy ContextInterface
implements
ConcreteClassA AlgorithmInterface
ConcreteClassB AlgorithmInterface
ConcreteClassC AlgorithmInterface
34
Specific 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()
35
Change 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( )

36
Strategy 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)

37
One 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

38

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

39
Add a third or fourth ...
  • public class ExpertStategy implements
    DrawCardStrategy
  • // Draw cards based on card counting
  • public boolean wantAnotherCard(Dealer
    theDealer)
  • // TBA ... complex algorithm

40
Used 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

41
Specific 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
Write a Comment
User Comments (0)
About PowerShow.com