Title: Introduction to Design Patterns and Ruby and C
1Introduction to Design PatternsandRuby and C
Overviews
Note In the following, class diagrams are often
used to clarify a design pattern. This does not
necessarily mean that the patterns will be
implemented exactly that way.
2Design Patterns
- Recurring solution design problems
- aim at flexible and reusable designs
- Inspired by Architectural Patterns from building
architecture - Basic design patterns Larman
- Information Expert, Creator,
- Gang of Four patterns
- Adapter, Proxy, Observer,
- There are many more patterns
- see CC438 home page for links
- WikiPedia entry is good
- http//en.wikipedia.org/wiki/Design_pattern_28com
puter_science29
3(Information) Expert Pattern
- Problem where to place attributes and
operations? - Solution assign a responsibility to a class that
has the information necessary to fulfil it - applies to responsibilities for doing something
(-gt operations) and knowing something (-gt
attributes) - let the expert take care of it
- Example calculate area in class Rectangle, not
in a derived class or another class.
4Creator Pattern
- Problem Who is responsible for creating objects
of class A? - Solution Assign class B the responsibility to
create objects of class A if - B aggregates A objects or
- B contains A objects or
- B keeps a record of A objects or
- B closely uses A objects
- Example In the Personnel example, the Person
objects could be created within a Company method
that reads person data from a database.
5Adapter Pattern
- Problem How to resolve incompatible interfaces?
- Solution Introduce an adapter that converts one
interface to another. - structural pattern, also known as a wrapper
- Example see Address/Comparable below
- Two variations
- Class adapter uses implementation inheritance
- Object adapter uses delegation
- Adapter pattern keeps existing classes unchanged
- of course, in some situations it can be easier to
change those classes/objects instead of
introducing adapters.
6Class Adapter
The Adapter extends the Adaptee so that it
provides the interface expected by the
client. Client and Adaptee classes are unchanged.
7Class Adapter Example
Collections void sort(List list)
client
Adaptee
Address boolean less(a1) boolean
equals(a1)
interface Comparable int compareTo(o)
AdaptedAddress int compareTo(o)
8Factory Method
- Problem how to allow flexibility when creating
objects from possibly different classes? - Solution A factory method can create objects
belonging to different classes within an
inheritance hierarchy. - Example Introduce a class ListFactory with a
method makeList() that chooses at runtime between
two standard list implementations. - control in one place which kind of lists are
used. - Analogy real factories which allow production of
different models, for example cars.
9Factory Method ListFactory
ListFactory - typeString ArrayList
makeList() List getType() String
setType(tString) boolean
Clients call makeList()instead of List
constructors
Can you think of an example of a factory used in
connection with JDBC?
10Abstract Factory Motivation
- Problem how to create compatible families of
objects? - Example Consider a user interface toolkit like
Java Swing that supports multiple looks and feel
standards such as Metal, Motif or Windows. - How to code a user interface that is portable
across different look and feel standards? - Solution generalisation of factory method
- a factory that can produce families of related or
dependent objects (product suite)
11Abstract Factory
Factory createProductA() createProductB()
Client
ProductA
ProductA1
ProductA2
ConcreteFactory1createProductA() createProductB()
ProductB
ProductB2
ProductB1
ConcreteFactory2 createProductA() createProductB()
12Abstract FactoryGUI Components
GUIFactory createWindow() createButton()
Client
Window
MotifWindow
MacWindow
MotifFactorycreateWindow() createButton()
Button
MacButton
MotifButton
MacFactory createWindow() createButton()
13Usage of Abstract Factory
- Client obtains a concrete factory object
- - often passed as parameter
- Clients calls factory methods to create objects.
- Client uses objects via their abstract
interfaces. - Example
- public void aboutWindow (GUIFactory f)
- Window w f.createWindow()
- Button b f.createButton(Ok)
- w.add(b)
-
14 Abstract Factory Pattern Applicability
- Useful in the following situations
- The system should be independent of how its
products are created, composed or represented - A system should be configurable with one of
several families of objects. - The system should be flexible to allow for a
future changes of the object family. - A system must use just one of a set of families
of product objects.
15Command Pattern Motivation
- Encapsulating a request as an object allows to
- parameterize clients with different requests
- queue or log requests, and
- support command stack operations
- Useful for example for
- undo/redo
- logging
- database transaction buffering
16Command Pattern Editor with Unlimited Undos
17A Command Pattern Sequence Diagram
Editor
rRectangle
UndoQueue
dragMouse()
mcCommand
create(move,r,x,y)
execute()
move(x,y)
add(mc)
18Command Pattern Example Editor
calls
EditorCommand execute()
MenuItem
Menu
Document copy()paste()
CopyCommand execute()
calls
PasteCommand execute()
calls
- Command methods execute(), store(), undo(),
redo() - Concrete command objects implement the abstract
method execute() by delegation to appropriate
Document methods.
19Command Pattern
Command execute()
calls
Subsystem
Receiver action1() action2()
ConcreteCommand1 execute()
calls
ConcreteCommand2 execute()
calls
- Command defines services common to all
ConcreteCommand objects. - Decoupling of Subsystem and Receiver only
ConcreteCommands interact with EntityObject.
20Structuring Objects
Commands (Application Layer)
Invoker (Presentation Layer)
UndoQueue
Menu
MoveCommand
MouseEvent
Triangle
Rectangle
Editor
Circle
Receiver (Domain objects)
21Observer Pattern
- Problem state changes in an object need to be
published to several subscriber objects. - Solution introduce an Observer interface that is
implemented by subscribers. The publisher can
dynamically register subscribers and notify them
when an event occurs. - Also called Publish and Subscribe
- Interface provided in Java SDK
- Implemented and used in Swing
- Related Model View Controller architectures,
Suns JSP Model2 architecture
22Observers
Subject C\teaching\cc271.1.ppt
23Observer Pattern
Observable addObserver() deleteObserver() n
otifyObservers()
interface Observerupdate()
Subject -state getState() setState()
ConcreteObserver observerState update()
24Observer Pattern Sequence Diagram Example Rename
File to CC271.ppt.BAK
w2DirWin
w1DirWin
cc271pptFileFile
addObserver()
addObserver()
setName(cc271.ppt.BAK)
notifyObservers()
update()
update()
getName()
cc271.ppt.BAK
getName()
cc271.ppt.BAK
25Observer Pattern Remarks
- Observers need to be informed about state changes
in a Subject object. - Observers call addObserver() in order to be added
to the list of observers of a subject. - When a noteworthy change of state in a subject
occurs, it invokes its notifyObservers() method. - this iteratively invokes the update() method of
each concrete observer of that subject. - Note that Observable is a concrete class
26Data Access Object (DAO) Pattern
- Most applications require some form of
persistence - It is possible to write code throughout an
application that makes specific data accesses - E.g. to RDB, OODB, XML File or DB, File Store
- The DAO pattern places all the storage /
retrieval methods in a specific group of classes - Separate from the main application
- Advantages can plug and play various DBs
- Disadvantages can make code more complex
- Think back to assignment 1
27More Patterns
- Façade Pattern
- Gives a simpler interface to a more complex class
or set of classes - Example an easier Date class for Java
- The easy Date constructor was deprecated
- Gregorian Calender hard work Façade would
simplify - Model View Controller (MVC) Pattern
- Predates the term design pattern
- Separates model (data) and control code from the
presentation
28Design Patterns Criticism (WikiPedia)
- Targets the wrong problem
- The need for patterns results from using computer
languages or techniques with insufficient
abstraction ability. - Many patterns exist to overcome limitations of
languages such as Java (though Java continues to
improve) - Lacks formal foundations
- Unlike components, does not provide reuse
- A pattern must be programmed anew into each
application that uses it. Some authors see this
as a step backward from software reuse as
provided by components. - Leads to inefficient solutions
- Code may be coerced to fit pattern in some
unnatural way - Does not differ significantly from other
abstractions - E.g. Software architectures such as MVC predated
pattterns
29Design Pattern Summary
- Provide template solutions to common problems
- May help to achieve design goals such as
extensibility, maintainability and efficiency - Often use interfaces/ abstract classes and
delegation to achieve flexibility - Can be applied to classes and subsystems
- Definitely something to keep in your mental
toolkit! - Be inspired but not enslaved by them!!!
30Exercise
- Consider the StatisticalSummary class studied
previously in the course - public class StatisticalSummary
- public void add(Number x)
- public double mean()
- public double sdev()
-
-
- Which of the above design patterns describes this
best?
31Ruby and C Overview
- Most of this course has studied object-oriented
design in the context of the Java programming
language - Ruby and C are modern alternative OO languages
- C is very similar to Java
- Ruby is rather different!
- These slides cover some of the main features
- With some sample code
32Java, C and Ruby all have
- Memory management
- Allocate with new, system takes care of GC
- Threads
- Object serialisation
- Single implementation inheritance
- Ruby adds module mixins
- These add methods to an existing class
33C versus Java
- Google for many comparisons of these two
- But beware most are out of date!
- And only consider Java pre 1.5
- A good one is here
- http//www.25hoursaday.com/CsharpVsJava.html
- An exercise go through the list at the link
above and see which features are still missing in
Java 1.5 - Not many!
- C has
- Delegates (essentially method pointers)
- Pointers (in unsafe code)
- Call by reference for primitive types enables
swap(a,b) - True multi-dimensional arrays (more efficient
than jagged) - Properties (x.name Joe instead of
x.setName(Joe) - x.name calls the set method
- Different conventions e.g. method names begin
upper-case
34Consider Practical Points
- IDE support
- VisualStudio for C and .NET
- Java has many alternatives
- Intellij, Eclipse, NetBeans,
- API support
- C is good (and also has XNA Platform !!!)
- Java is probably even better in general
- Java runs on JVM
- C runs on CLR (Common Language Runtime)
- Interoperate with any .NET language
- C compiles down to executables
- Java runs on JVM (JIT compiled)
- Java is more platform independent
- Mobile C best for PocketPC, Java best for phone
35C Spotlight Delegates
- Perhaps the best C feature over Java
- Useful for event-driven programming
- Javas equivalent is to define an interface
- E.g. MouseListener
- But then any implementation of MouseListener must
implement all the methods of that interface - A C delegate need only implement the relevant
method signature - Note in Java, an alternative way to do this is
to use reflection, and pass a java.lang.reflect.Me
thod object - Bit clumsy, and has run-time overhead
36GUI Example (Tetris)
- Within the View class init method
- this.KeyDown new KeyEventHandler(TryKeyP
ressed) - This method is then defined with the appropriate
signatures - public void TryKeyPressed( object sender,
KeyEventArgs e) - controller.handleKey(e.KeyCode)
- Invalidate() // causes a repaint
-
37Ruby
- Released in 1995
- Developed by Yukihiro "Matz" Matsumoto
- Currently in version 1.85
- Multi-paradigm
- Procedural, OO, Functional, Scripting
- Concise syntax!
- Interpreted
- So typically slower than Java or C
- Perhaps hundreds of times slower in some cases
- Byte-code compilation in future release?
- Very powerful
38Ruby Resources
- Good WikiPedia entry
- http//en.wikipedia.org/wiki/Ruby_28programming_l
anguage29 - See also
- http//www.ruby-lang.org/en/ (homepage)
- http//tryruby.hobix.com/ (try in browser)
- Ruby interpreter available for many platforms
- Windows, Mac, Linux, Unix
- See also JRuby
- Ruby interpreter written in Java
- Full access to Java API
- Also Groovy Ruby inspired scripting language
for Java
39Some Ruby Fundamentals
- Everything is an Object!
- Unlike Java and C which define primitive types
also - Duck Typing
- If it walks like a duck, and quacks like a duck
- A method can be called on any object that
supports that method - Strong but dynamic typing
- Built in collection types (lists, arrays, maps)
- Can treat XML, HTML syntax natively
- Also native regular expressions
- This power is exploited in Ruby on Rails
- a rapidly growing web application system
40Hello World in Ruby
- puts Hello World
- Yes, thats it!
- Compare this with the Java equivalent
- Not a public static void main in sight!
- In following examples, note that is the
comment character
41Everything an Object
- Everything, including a literal,
- is an object, so this works
- -199.abs 199
- "ruby is cool".length 12
- "Rick".index("c") 2
- "Nice Day Isn't It?".split(//).uniq.sort.join
- " '?DINaceinsty"
- what would happen if the uniq was omitted?
42Collections
- Arrays
- Note mixed type
- Call methods directly on them
- a 1, 'hi', 3.14, 1, 2, 4, 5
- a2 3.14
- a.reverse 4, 5, 2, 1, 3.14, 'hi', 1
- a.flatten.uniq 1, 'hi', 3.14, 2, 4, 5
- Hashmaps
- h"Libor" gt "4B.525"
- h.store("Simon", "4B.526")
- h.fetch("Simon") "4B.526"
- h.fetch("Libor") "4B.525"
43Word Count Example
- Note w for creating an array of words
- Hashmap init and iter
- words wthe cat sat on the mat
- def count(words)
- map Hash.new(0) initialise entries to zero
- words.each word
- mapword mapword 1
-
- map
- end
- now test it
- map count words
- map.each k,v puts k " " v.to_s
44Word Count Output
- C\courses\cc438\rubygt\ruby\bin\ruby wc.rb
- mat 1
- cat 1
- sat 1
- the 2
- on 1
- Note also how def was used to define a method
- And the last expression in the method is its
return value - Lab Exercise implement Java solution to this
problem, and compare with Ruby version
45Example Retrieve image filenames from web page
- require 'net/http'
- h  NetHTTP.new( 'www.pragmaticprogrammer.co
m', 80) - resp, data  h.get('/index.html', nil)
- if resp.message  "OK"  Â
- data.scan(/ltimg src"(.?)"/)  x puts x end
- produces
- images/title_main.gif
- images/dot.gif
- images/dot.gif
- images/dot.gif
-
- images/dot.gif
- Note much shorted than equivalent Java prog
46Multi-threaded web page retrieval
- require 'net/http'
- pages  w(www.rubycentral.com
        www.awl.com         www.pragmaticprogramm
er.com ) - threads Â
- for page in pages
-   threads ltlt Thread.new(page)  myPage
-     h  NetHTTP.new(myPage, 80)  Â
-   puts "Fetching myPage" Â
-    resp, data  h.get('/', nil )
-     puts "Got myPage  resp.message"  Â
- end
- threads.each  aThread  aThread.joinÂ
47Produces
- Fetching www.rubycentral.com
- Fetching www.awl.com
- Fetching www.pragmaticprogrammer.com
- Got www.rubycentral.com  OK
- Got www.pragmaticprogrammer.com  OK
- Got www.awl.com  OK
- Q. What evidence is there of multi-threading in
the above output?
48Ruby Summary
- Very powerful and flexible
- Can write much shorter programs than in Java or
C - But are they as easy to understand?
- Are they as maintainable?
- Ruby is growing rapidly in popularity
- Well worth learning
- Also helps you streamline your Java code
- Also see JRuby combines succinct nature of Ruby
with extensive APIs of Java - And also Groovy