2. Contents
I. Introduce to design pattern through example
1. Problem
2. Issues
3. Solutions
II. Design patterns
III. Design patterns classification
3. Problem
1. Simulate Duck application
SimUDuck Initial design
Supper class
1 (abstract class)
2
3 4
1. show a large variety
of duck species swimming
2. making quacking sounds
Inherited classes
(concrete classes)
6. Solution is …inheritance?
Override fly() method to do nothing
1
No fly, no quack
2
3
Disadvantage
of inheritance?
1. Code is duplicated across subclasses
2. Changes can unintentionally affect others Difficult to
3. Hard to gain knowledge of all object behaviors
maintain
4. Runtime behavior change are difficult
7. Solution is …interface?
1. Flyable() interface. 1 What happen if you need
2. Spec will keep changing to make a little
2
3. Override fly() and quack() change to the flying
Behavior….in all of 100
the flying Duck
subclasses?
1. Interface solves part of the problem
3
2. Completely destroys code reuse for those
behaviors
8. Solution is …CHANGE
No matter how well you design an application, over time an
application must grow and change or it will die. 1
2
4
3
Change
5
Stable
9. Solution
1 fly() and quack() are the parts of the
Duck class that vary across ducks
2
Separate change and stable
How to design
3
Duck behaviors?
10. Solution
What we want:
1 1. Instantiate a particular object and initialize it with specific type of flying behavior
2. Can change flying behavior at runtime.
2 use an interface to
~ API
represent each behavior
3
4
Any behaviors changed will not
5 affected to Duck class and
it’s child classes
11. Program to an interface vs Program to an implementation
Program to an implementation Have demo as quick as possible
Don’t care about extend/upgrade/maintain
Program to an interface
assign the concrete implementation
object at runtime
Take time to design but it is flexible
13. Implementing the Duck Behaviors
1 Easy to reuse for other objects (not duck)
2 Easy to extend/modify that make no side effect
14. Integrating the Duck Behavior
1 Add two instance variables to the Duck class
2 Implement performQuack()
don’t care
what kind of
object it is.
Care about
how to quack()
15. Integrating the Duck Behavior
3 flyBehavior and quackBehavior instance variables are set
3.2
3.1
3.3
27. Design patterns
1. General reusable solution to a commonly occurring problem
within a given context in software design
2. Type of patterns
Creational patterns
Structural patterns
Behavioral patterns