Project Based Learning (A.I).pptx detail explanation
Software Design Patterns Lecutre (Intro)
1. P R E S E N T E D B Y S A N G E E T A M E H T A
E E C S 8 10
U N I V E R S I T Y O F K A N S A S
O C T O B E R 2 0 0 8
Design Patterns
2. 2
Contents
4/11/2024
University of Kansas
2
Introduction to OO concepts
Introduction to Design Patterns
What are Design Patterns?
Why use Design Patterns?
Elements of a Design Pattern
Design Patterns Classification
Pros/Cons of Design Patterns
Popular Design Patterns
Conclusion
References
3. 3
What are Design Patterns?
What Are Design Patterns?
Wikipedia definition
“a design pattern is a general repeatable solution to a
commonly occurring problem in software design”
Quote from Christopher Alexander
“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” (GoF,1995)
4/11/2024
3
University of Kansas
4. 4
Why use Design Patterns?
Good Design
Maintainability
Extensibility
Scalability
Testability
Reusablilty
Design Principles
Program to an interface, not an implementation
High cohesion
Low coupling
Open-Closed
Separation of concerns
Design Patterns
Singleton
Abstract Factory
DAO
Strategy
Decorator
T
h
e
r
o
a
d
t
o
g
o
o
d
d
e
s
i
g
n
4/11/2024
University of Kansas
5. 5
Why use Design Patterns?
Design Objectives
Good Design (the “ilities”)
High readability and maintainability
High extensibility
High scalability
High testability
High reusability
4/11/2024
University of Kansas
7. 7
Elements of a Design Pattern
A pattern has four essential elements (GoF)
Name
Describes the pattern
Adds to common terminology for facilitating communication (i.e.
not just sentence enhancers)
Problem
Describes when to apply the pattern
Answers - What is the pattern trying to solve?
4/11/2024
University of Kansas
8. 8
Elements of a Design Pattern (cont.)
Solution
Describes elements, relationships, responsibilities, and
collaborations which make up the design
Consequences
Results of applying the pattern
Benefits and Costs
Subjective depending on concrete scenarios
4/11/2024
University of Kansas
10. 10
Pros/Cons of Design Patterns
Pros
Add consistency to designs by solving similar problems the same
way, independent of language
Add clarity to design and design communication by enabling a
common vocabulary
Improve time to solution by providing templates which serve as
foundations for good design
Improve reuse through composition
4/11/2024
University of Kansas
11. 11
Pros/Cons of Design Patterns
Cons
Some patterns come with negative consequences (i.e. object
proliferation, performance hits, additional layers)
Consequences are subjective depending on concrete scenarios
Patterns are subject to different interpretations, misinterpretations,
and philosophies
Patterns can be overused and abused Anti-Patterns
4/11/2024
University of Kansas
12. 12
Popular Design Patterns
Let’s take a look
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
4/11/2024
University of Kansas
13. 13
Strategy Definition
Defines a family of algorithms, encapsulates
each one, and makes them interchangeable.
Strategy lets the algorithm vary
independently from clients that use it.
4/11/2024
University of Kansas
14. Design Principles
Identify the aspects of your application that vary and separate them
from what stays the same
Program to an interface, not an implementation
Favor composition over inheritance
4/11/2024
University of Kansas
14
18. 18
Strategy
Pros
Provides encapsulation
Hides implementation
Allows behavior change at runtime
Cons
Results in complex, hard to understand code if overused
4/11/2024
University of Kansas
19. 19
Observer Definition
Defines a one-to-many dependency between objects so
that when one object changes state, all of its
dependents are notified and updated automatically.
4/11/2024
University of Kansas
20. Design Principles
Identify the aspects of your application that vary and separate them
from what stays the same
Program to an interface, not an implementation
Favor composition over inheritance
Strive for loosely coupled designs between objects that interact
4/11/2024
University of Kansas
20
24. 24
Observer
Pros
Abstracts coupling between Subject and Observer
Supports broadcast communication
Supports unexpected updates
Enables reusability of subjects and observers independently of each
other
Cons
Exposes the Observer to the Subject (with push)
Exposes the Subject to the Observer (with pull)
4/11/2024
University of Kansas
25. 25
Singleton Definition
Ensure a class only has one instance and provide a
global point of access to it.
4/11/2024
University of Kansas
29. 29
Singleton
cmp Proxy
public class Singleton {
private static Singleton instance = null;
protected Singleton() {
//Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public class SingletonInstantiator {
public SingletonInstantiator() {
Singleton instance = Singleton.getInstance();
Singleton anotherInstance = new Singleton();
......
}
4/11/2024
University of Kansas
30. 30
Singleton
Pros
Increases performance
Prevents memory wastage
Increases global data sharing
Cons
Results in multithreading issues
4/11/2024
University of Kansas
31. 31
Patterns & Definitions – Group 1
Strategy
Observer
Singleton
Allows objects to be notified
when state changes
Ensures one and only one
instance of an object is created
Encapsulates inter-changeable
behavior and uses delegation to
decide which to use
4/11/2024
University of Kansas
31
4/11/2024
University of Kansas
32. 32
Patterns & Definitions – Group 1
Strategy
Observer
Singleton
Allows objects to be notified
when state changes
Ensures one and only one
instance of an object is created
Encapsulates inter-changeable
behavior and uses delegation
to decide which to use
4/11/2024
University of Kansas
32
4/11/2024
University of Kansas
33. 33
Patterns & Definitions – Group 1
Strategy
Observer
Singleton
Allows objects to be notified
when state changes
Ensures one and only one
instance of an object is created
Encapsulates inter-changeable
behavior and uses delegation
to decide which to use
4/11/2024
University of Kansas
33
4/11/2024
University of Kansas
34. 34
Patterns & Definitions – Group 1
Strategy
Observer
Singleton
Allows objects to be notified
when state changes
Ensures one and only one
instance of an object is created
Encapsulates inter-changeable
behavior and uses delegation to
decide which to use
4/11/2024
University of Kansas
34
4/11/2024
University of Kansas
35. 35
Decorator Definition
Attaches additional responsibilities to an object
dynamically. Decorators provide a flexible alternative
to sub-classing for extending functionality.
4/11/2024
University of Kansas
36. Design Principles
Identify the aspects of your application that vary and separate them
from what stays the same
Program to an interface, not an implementation
Favor composition over inheritance
Strive for loosely coupled designs between objects that interact
Classes should be open for extension, but closed for modification
4/11/2024
University of Kansas
36
38. 38
Decorator - Problem
class Decorator
Beverage
- description: String
- milk: boolean
- soy: boolean
- whip: boolean
+ cost() : double
{
//Add all the condiment's costs to the beverage cost
//The boolean methods help in determining if the
condiments
//have been added to the beverage.
//return the total cost
}
+ getDescription() : String
+ hasMilk() : boolean
+ hasSoy() : boolean
+ hasWhip() : boolean
+ setMilk(boolean) : void
+ setSoy(boolean) : void
+ setWhip(boolean) : void
DarkRoast
+ cost() : double
{
return 1.99 + super.cost()
//return the beverage's cost and add it to the result of calling
//the superclass, Beverage's cost
}
+ DarkRoast() : void
{
description = "Most Excellent Dark Roast"
}
Espresso
+ cost() : double
{
return 2.10 + super.cost();
}
+ Espresso() : void
{
description = "Very fine Espresso"
}
4/11/2024
University of Kansas
39. 39
Decorator - Solution
class Decorator
Beverage
- description: String = "Unknown Beverage"
+ cost() : double
{
//An abstract method. Implemented in the subclasses.
}
+ getDescription() : String
{
return description;
}
DarkRoast
+ cost() : double
{
return 1.99;
}
+ DarkRoast() : void
{
description = "Most Excellent Dark
Roast"
}
Espresso
+ cost() : double
{
return 2.10 ;
}
+ Espresso() : void
{
description = "Very fine Espresso"
}
CondimentDecorator
+ getDescription() : String
{
//abstract method..Do nothing
}
Mocha
- beverage: Beverage
+ cost() : double
{
//Adds the cost of the condiment to the cost of
the decorated beverage
return .20 + beverage.cost();
}
+ getDescription() : String
{
//Attaches the name of the condiment to the
beverage name
return beverage.getDescription + ", Mocha";
}
+ Mocha(Beverage) : void
{
//Stores a reference to the Beverage in
consideration.
this.beverage = beverage;
}
Milk
- beverage: Beverage
+ cost() : double
+ getDescription() : String
4/11/2024
University of Kansas
40. 40
Decorator
Pros
Extends class functionality at runtime
Helps in building flexible systems
Works great if coded against the abstract component type
Cons
Results in problems if there is code that relies on the concrete
component’s type
4/11/2024
University of Kansas
41. 41
Proxy Definition
Provides a surrogate or placeholder for another object
to control access to it
4/11/2024
University of Kansas
45. 45
Proxy
Pros
Prevents memory wastage
Creates expensive objects on demand
Cons
Adds complexity when trying to ensure freshness
4/11/2024
University of Kansas
46. 46
Facade Definition
Provides a unified interface to a set of interfaces in a
subsystem. Façade defines a higher level interface
that makes the subsystem easier to use.
4/11/2024
University of Kansas
47. Design Principles
Identify the aspects of your application that vary and separate them
from what stays the same
Program to an interface, not an implementation
Favor composition over inheritance
Strive for loosely coupled designs between objects that interact
Classes should be open for extension, but closed for modification
Principle of least knowledge – talk only to your immediate friends
4/11/2024
University of Kansas
47
51. 51
Facade
Pros
Makes code easier to use and understand
Reduces dependencies on classes
Decouples a client from a complex system
Cons
Results in more rework for improperly designed Façade class
Increases complexity and decreases runtime performance for large
number of Façade classes
4/11/2024
University of Kansas
52. 52
Adapter Definition
Converts the interface of a class into another interface
the clients expect. Adapter lets classes work together
that couldn’t otherwise because of incompatible
interfaces.
4/11/2024
University of Kansas
56. 56
Adapter
Pros
Increases code reuse
Encapsulates the interface change
Handles legacy code
Cons
Increases complexity for large number of changes
4/11/2024
University of Kansas
57. 57
Patterns & Definitions – Group 2
Decorator
Proxy
Façade
Adapter
Simplifies the interface of
a set of classes
Wraps an object and
provides an interface to it
Wraps an object to
provide new behavior
Wraps an object to control
access to it
4/11/2024
University of Kansas
57
4/11/2024
University of Kansas
58. 58
Patterns & Definitions – Group 2
Decorator
Proxy
Façade
Adapter
Simplifies the interface of
a set of classes
Wraps an object and
provides an interface to it
Wraps an object to
provide new behavior
Wraps an object to control
access to it
4/11/2024
University of Kansas
58
4/11/2024
University of Kansas
59. 59
Patterns & Definitions – Group 2
Decorator
Proxy
Façade
Adapter
Simplifies the interface of
a set of classes
Wraps an object and
provides an interface to it
Wraps an object to
provide new behavior
Wraps an object to control
access to it
4/11/2024
University of Kansas
59
4/11/2024
University of Kansas
60. 60
Patterns & Definitions – Group 2
Decorator
Proxy
Façade
Adapter
Simplifies the interface of
a set of classes
Wraps an object and
provides an interface to it
Wraps an object to
provide new behavior
Wraps an object to control
access to it
4/11/2024
University of Kansas
60
4/11/2024
University of Kansas
61. 61
Patterns & Definitions – Group 2
Decorator
Proxy
Façade
Adapter
Simplifies the interface of
a set of classes
Wraps an object and
provides an interface to it
Wraps an object to
provide new behavior
Wraps an object to control
access to it
4/11/2024
University of Kansas
61
4/11/2024
University of Kansas
62. 62
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
4/11/2024
University of Kansas
62
4/11/2024
University of Kansas
63. 63
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
4/11/2024
University of Kansas
63
4/11/2024
University of Kansas
64. 64
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
Behavioral
4/11/2024
University of Kansas
64
4/11/2024
University of Kansas
65. 65
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
Behavioral
Creational
4/11/2024
University of Kansas
65
4/11/2024
University of Kansas
66. 66
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
Behavioral
Creational
Structural
4/11/2024
University of Kansas
66
4/11/2024
University of Kansas
67. 67
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
Behavioral
Creational
Structural
Structural
4/11/2024
University of Kansas
67
4/11/2024
University of Kansas
68. 68
Pattern Classification
Strategy
Observer
Singleton
Decorator
Proxy
Façade
Adapter
Behavioral
Behavioral
Creational
Structural
Structural
Structural
4/11/2024
University of Kansas
68
4/11/2024
University of Kansas
70. Conclusion - Design Principles
Identify the aspects of your application that vary and separate them
from what stays the same
Program to an interface, not an implementation
Favor composition over inheritance
Strive for loosely coupled designs between objects that interact
Classes should be open for extension, but closed for modification
Principle of least knowledge – talk only to your immediate friends
4/11/2024
University of Kansas
70
scalability deals with how the application can grow or shrink. Extensibility deals with how other people, systems, etc. can take the existing code and add on to it without affecting the base
Name – helps in having a common vocabulary for communication
Problem – a list of conditions to be met before the pattern can be applied
Solution – doesn’t describe a concrete design or implementation, because pattern is like a template
Consequences – seldomly discussed but very imp…generally time and space tradeoffs…May address implementation and language issues as well. Listing consequences help in evaluating and understanding patterns.
The purpose criterion sorts the patterns in three groups. Creational, Structural and Behavioural.
Creational patterns deals with object creation. Class scope creational patterns defer some part of the object creation process to subclasses. Object scope creational patterns defer it to another object.
Structural patterns deals with compositions of objects and classes. Structural class patterns are based on inheritance to build a structure. Structural object patterns use object references to build a structure.
Behavioural patterns are used to distribute responsibility between classes and objects. The patterns define how the classes and objects should interact, and what responsibilities each participant has. Behavioural class patterns are based on inheritance. They are mostly concerned with handling algorithms and flow of control. Behavioural object patterns describe how objects can cooperate to carry out tasks that no single object can carry out alone.
Object proliferation - you'll end up with a lot extra little objects when you implement the design pattern. So you have quite a few small classes that don't really do anything. It ends up taking tons of classes to do something really small
an anti-pattern is something that does not work, or is so brittle that it gives the appearance of working, but is easily broken.
One common anti-pattern: using inheritance from a utility class (e.g., Hashtable) rather than delegation. Inheritance is used very often in this context, and even works, but has the following problems:
It causes the derived class to rely on the internals of a base class which is out of the control of the developer. While the utility classes normally are stable and fairly similar across VMs, some innocuous change in the future could break the derived class.
It muddies the business meaning of the derived class. For example, an order is not a vector, although an order may contain a vector of line items.
Interfaces are fundamental in OO. Objects are known only thru their interfaces…there is no other way of knowing what is inside. Interface hides the implementation details. This means that 2 diff objects can have 2 totally diff implementations for the same interface.
Inheritance (white box) – internal details visible, static- compile time. Inheritance sometimes break encapsulation.
Composition (black box) – well defined interface, internal details not visible, dynamic – run time
Help in building flexible systems because they minimize interdependency between objects.
A well defined interface is all that is needed.
The ability to add new objects without affecting the existing objects.
The only thing that the Subject knows about the Observer is that it implements a certain interface
Can add new observers at any time
We never need to modify the subject to add new types of observers
Changes to either Subject or Observers will not affect the other.
Talk about push and pull.
Fro the technical folks…will this compile?
Ans: yes, since the constructor is protected.
Solution: private constructor (but no subclassing then)
separate package for the Singleton class.
Multithreading issues…can be avoided, synchronizing the getInstance() method.
Public static synchronized Singleton getInstance()
Static initialization instead of lazy initialization.
Private static Singleton instance = new Singleton();
Seem like a contradiction.
There are techniques, example Observer. We can extend the Subject by adding new Observers without actually adding code to the Subject.
Also called Open-Closed Principle.
Be careful, can result in complex code.
If there
Proxy and Decorator very similar…
Decorator adds behavior to a class while proxy controls access to it.
The Proxy class might have stale information, in which case we might have to add some extra logic to ensure freshness…Depending on the logic, complexity level might increase.
Minimize the number of classes an object interacts with. This principle prevents us from creating designs with large number of coupled classes such that changes in one part of the system cascades to other parts. Lots of dependencies results in fragile, expensive, and complex systems.
Interfaces are fundamental in OO. Objects are known only thru their interfaces…there is no other way of knowing what is inside. Interface hides the implementation details. This means that 2 diff objects can have 2 totally diff implementations for the same interface.
Inheritance (white box) – internal details visible, static- compile time. Inheritance sometimes break encapsulation.
Composition (black box) – well defined interface, internal details not visible, dynamic – run time