CSc 335 - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

CSc 335

Description:

These s were written by Richard Snodgrass. ... Elisabeth Freeman, Kathy Sierra, and Bert Bates, O'Reilly Media, October, 2004. ... – PowerPoint PPT presentation

Number of Views:37
Avg rating:3.0/5.0
Slides: 27
Provided by: RTS8
Category:
Tags: bert | csc

less

Transcript and Presenter's Notes

Title: CSc 335


1
Design Patterns
CSc 335 Object-Oriented Programming and
Design Fall 2006
2
Acknowledgements
  • These slides were written by Richard Snodgrass.
    Some slides from Rick Mercer and Martin Stepp
    were used.
  • They include information in Design Patterns
    Elements of Reusable Object-Oriented Software, by
    Erich Gamma, Richard Helm, Ralph Johnson, and
    John Vlissides, Addison-Wesley Publishing
    Company, 1995.
  • Some information was taken from Refactoring
    Improving the Design of Existing Code, by Martin
    Fowler, Addison-Wesley Publishing Company, 1999.
  • Inspiration was also taken from Head First Design
    Patterns, by  Eric Freeman, Elisabeth Freeman,
    Kathy Sierra, and Bert Bates, OReilly Media,
    October, 2004.

3
Outline
  • Overview of Patterns
  • Iterator
  • Strategy

4
The Germ of this Approach
  • Christopher Alexander, architect
  • A Pattern Language---Towns, Buildings,
    Construction (1977)
  • Timeless 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, bureaucratic memos, political speeches

5
Gang of Four (GoF) Book
  • Design Patterns Elements of Reusable
    Object-Oriented Software, Addison-Wesley
    Publishing Company, 1994.
  • Dr. Erich Gamma, then Software Engineer,
    Taligent, Inc. now at Object Technology
    International as the technical director of the
    Zurich lab in Switzerland.
  • Dr. Richard Helm, then Senior Technology
    Consultant, DMR Group now at the Boston
    Consulting Group.
  • Dr. Ralph Johnson, then and now at University of
    Illinois, Computer Science Department now a
    Research Associate Professor.
  • Dr. John Vlissides, then a researcher at IBM
    Thomas J. Watson Research Center.

6
GoF Patterns
  • Creational Patterns
  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton
  • Structural Patterns
  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Façade
  • Flyweight
  • Proxy
  • Behavioral Patterns
  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

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

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

9
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?

10
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?

11
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)

12
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

13
Patterns
  • This book defined 23 patterns, classified into
    three categories.
  • Creational patterns, which deal with the process
    of object creation.
  • Structural patterns, which deal primarily with
    the static composition and structure of classes
    and objects.
  • Behavioral patterns, which deal primarily with
    dynamic interaction among classes and objects.
  • Many other patterns have been introduced by
    others.
  • For 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.
  • Hundreds of patterns have been documented since
    other examples include telecommunications
    patterns, pedagogical patterns, analysis
    patterns, and indexing patterns.

14
A Common Style for Patterns
  • Formats of pattern writers vary, but a pattern
    description usually has at least these four
    things.
  • A name
  • 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

15
Style for Describing Patterns
  • We will use this structure in these slides.
  • Pattern name
  • Recurring problem what problem the pattern
    addresses
  • Solution the general approach of the pattern
  • Also known as other names for the pattern
  • UML for the pattern
  • Participants a description of the classes in the
    UML
  • Explanation
  • Use Example(s) examples of this pattern, in Java

16
Outline
  • Overview of Patterns
  • Iterator
  • Strategy

17
Iterator Pattern
  • Recurring Problem
  • You have an aggregate data type. How can you
    access the elements sequentially without exposing
    its underlying representation?
  • Solution
  • Provide a separate object, an iterator, that can
    retain the current position, and go to the next
    element.
  • Also known as
  • Cursor

18
Use Example Collections Framework
  • The Collections framework has an Iterator
    interface.
  • boolean hasNext() Is the iterator positioned at
    the last element in the aggregate?
  • Object next() Move to the next element and return
    it.
  • void remove() Remove the object most recently
    returned by next().
  • The remove() method is optional. If an Iterator
    does not support this method, it throws
    java.lang.UnsupportedOperationException when
    invoked.
  • Collection has the method
    Iterator Iterator()

19
Use Example, cont.
  • An Iterator can be used to look through the
    elements of any kind of collection (as an
    alternative to a for loop).
  • Song song1 new Song("Cheryl Crowe", "Home",
    124, "Home.mid")
  • Song song2 new Song("Sting", "Fields of Gold",
    212, "gold.mp3")
  • Song song3 new Song("Beatles", "Help", 132,
    "Help.mid")
  • CollectionltSonggt allSongs new TreeSetltSonggt()
  • allSongs.add(song1) TreeSet
    could be ArrayList, LinkedList
  • allSongs.add(song2)
  • allSongs.add(song3)
  • // Iterate over all elements
  • IteratorltSonggt itr allSongs.iterator()
  • while (itr.hasNext())
  • Song s itr.next()
  • System.out.println(s.getArtist())

20
Strategy Pattern
  • Recurring Problem
  • We want to be able to switch strategies
  • Solution
  • Define a strategy as an interface, then
    instantiate multiple strategies as concrete
    classes
  • Also known as
  • Policy

21
Participants
  • Context
  • Maintains a reference to a Strategy object.
  • Example The content pane of a JFrame has a
    layout strategy that can be changed
  • Strategy
  • Declares an interface common to all supported
    algorithms AlgorithmInterface.
  • Example interface LayoutManager that defines
    methods that to place components
  • ConcreteStrategy
  • Implements the Algorithm interface.
  • Example BorderLayout, GridLayout, FlowLayout, ...

22
Layout Managers
  • There are five predefined layout managers in the
    javax.swing package
  • flow layout
  • border layout
  • card layout
  • grid layout
  • grid bag layout
  • Each container has a default layout manager
  • You can also create you own custom layout
    managers but not necessary here

23
A Layout Manager
  • By default, JFrame uses BorderLayout
  • getContentPane().setLayout(new FlowLayout())
  • Then when you add, things are added laid out
    according to the layout strategy

24
Flow Layout
  • Components are placed in a row from left to right
    in the order in which they are added
  • A new row is started when no more components can
    fit in the current row
  • Components are centered in each row

25
Example of FlowLayout in a JFrame
  • import java.awt.Container
  • import java.awt.FlowLayout
  • import javax.swing.JButton
  • import javax.swing.JFrame
  • public class FrameWithFlowLayout extends JFrame
  • public static void main(String args)
  • new FrameWithFlowLayout().setVisible(true)
  • public FrameWithFlowLayout()
  • setSize(200, 160)
  • Container contentPane this.getContentPane()
  • // Without changing layout manager, all
    buttons go to Center
  • contentPane.setLayout(new FlowLayout())
  • contentPane.add(new JButton("1"))
  • contentPane.add(new JButton("2"))
  • contentPane.add(new JButton("3"))
  • contentPane.add(new JButton("4"))

26
Grid Layout
  • Components are placed in a grid with a
    user-specified number of columns and rows
  • Each component occupies exactly one grid cell
  • Grid cells are filled left to right and top to
    bottom
  • All cells in the grid are the same size
  • Change the strategy like this to see the
    different arrangement
  • contentPane.setLayout(new GridLayout(3, 3))
Write a Comment
User Comments (0)
About PowerShow.com