0% found this document useful (0 votes)
6 views

SWEonline Design Patterns

Uploaded by

Mushfiqur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

SWEonline Design Patterns

Uploaded by

Mushfiqur Rahman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

Creational Patterns

1
UML Revisited

Aggregation: “is part of”

Composition: “is entirely made of”

Generalization

Dependency: “uses”
2
Creational Patterns to be Covered

ꟷFactory method
ꟷAbstract factory
ꟷBuilder
ꟷSingleton

Examples taken from:


https://www.tutorialspoint.com/design_pattern/
https://www.javatpoint.com/design-patterns-in-java

3
Factory Method

Intent • Define an interface for creating an object, but


let subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation
to subclasses.

Problem • A framework needs to standardize the


architectural model for a range of applications,
but allow for individual applications to define
their own domain objects and provide for their
instantiation.
• Enable the creator to defer product creation to
sub-class.

4
Solution

5
Example: Drawing

<<interface>> Client
Shape
+ draw()

Circle Square Rectangle ShapeFactory


+drawShape(type):Shape
+ draw() + draw() + draw()

6
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Similar implementation for Square and Circle

7
Example: Kiosk

<<interface>> Kiosk
PaymentProcessor
+ processPayment()

GetPayment
Cash CreditCard Coupon +getProcessor(type):
PaymentProcessor
+ prcessPayment() + prcessPayment() + prcessPayment()

8
Factory

9
10
11
Consequences
• Factory design pattern provides approach to code for interface rather
than implementation.
• Factory pattern removes the instantiation of actual implementation
classes from client code. Factory pattern makes our code more
robust, less coupled and easy to extend. For example, we can easily
change lower class implementation because client program is
unaware of this.
• Factory pattern provides abstraction between implementation and
client classes through inheritance.

12
Abstract Factory

Intent • Provide an interface for creating families of


related or dependent objects without
specifying their concrete classes.

Problem • A portable application needs to encapsulate


platform dependencies
• Consider an application that support multiple
look and feels.
• An application need to work with multiple
types of DBMS

13
Solution

14
Example: Car Factory
<<interface>> Client
HondaFactory
+ createEngine()
+ createTrans()

Engine

CivicFactory AccordFactory
+ createEngine() + createEngine()
+ createTrans() + createTrans()
CivicEngine AccordEngine

Transmission

CivicTrans AccordTrans

15
https://www.tutorialspoint.com/design_pattern/design_pattern
_quick_guide.htm

16
17
18
Abstract Factory

19
20
21
22
23
24
Consequences
• Isolates the concrete class
• Makes exchanging product family easy
• Promotes consistency among products
• Abstract Factory design pattern provides approach to code for
interface rather than implementation.
• Abstract Factory pattern is “factory of factories” and can be easily
extended to accommodate more products.
• Abstract Factory pattern is robust and avoid conditional logic of
Factory pattern.
• Supporting new types of products is difficult

25
Singleton

Intent • Ensure a class has only one instance, and


provide a global point of access to it.
• Encapsulated "just-in-time initialization" or
"initialization on first use".

Problem • Application needs one, and only one, instance


of an object. Additionally, lazy initialization and
global access are necessary.

26
Solution

SingletonClass
- instance: SingletonClass

- SingletonClass()
+ getInstance(): SingletonClass

27
Example: DB Connection Manger
public class DbConnection{

private static DbConnection instance=null;


private SQLConnection connection;

private DbConnection() {
connection = connectToDatabase(dbUser,dbPassword,dbName);
}

public static getDbConnection() {


if (instance== null )
instance = new DbConnection() ;

return instance;
}
}

DbConnection connection=DbConnection.getDbConnection();

28
Consequences
• Controlled access to sole instance

• Reduced namespace

• Permits variable number of instances

29
Builder

Intent • Separate the construction of a complex object


from its representation so that the same
construction process can create different
representations.
• Parse a complex representation, create one of
several targets.
Problem • An application needs to create the elements of
a complex aggregate. The specification for the
aggregate exists on secondary storage and one
of many representations needs to be built in
primary storage.

30
Solution

31
Examples

To create a computer,
different parts are assembled
depending upon the order
received by the customer
(e.g., a customer can demand
a 500 GB hard disk with an
Intel processor; another
customer can choose a 250
GB hard disk with an AMD
processor).

32
Consequences
• Lets you vary a product’s internal representation

• Isolates construction and representation

• Gives you finer control over the construction process

33
34
35
36
Builder

37
38
39
40
Structural Patterns

1
Motivation: Adapter

2
Adapter

Intent • Convert the interface of a class into another


interface clients expect. Adapter lets classes
work together that couldn't otherwise because
of incompatible interfaces.
• Wrap an existing class with a new interface.
Problem • An "off the shelf" component offers compelling
functionality that you would like to reuse, but
its "view of the world" is not compatible with
the philosophy and architecture of the system
currently being developed.

3
Solution

4
Example: Car Factory

Client

<<interface>>
PowerAdapter
+connectPower()

EuroInterface USInterface USSocket


+connectPower() +connectPower() +powerConnection()

5
6
7
8
Adapter

9
10
11
Consequences
• Allows pre-existing classes to be used in your code.

• Will not work if existing class is missing some key behavior.

12
Motivation: Decorator

13
Decorator

Intent • Attach additional responsibilities to an object


dynamically. Decorators provide a flexible
alternative to subclassing for extending
functionality.
• Client-specified embellishment of a core object
by recursively wrapping it.
• Wrapping a gift, putting it in a box, and
wrapping the box.
Problem • You want to add behavior or state to individual
objects at run-time. Inheritance is not feasible
because it is static and applies to an entire
class.

14
Solution

15
16
17
18
Decorator

19
20
21
22
23
Consequences
• More flexibility than static inheritance

• Pay-as-you-go approach

• Lots of little objects

24
Composite

Intent • Compose objects into tree structures to


represent whole-part hierarchies. Composite
lets clients treat individual objects and
compositions of objects uniformly.
• Recursive composition
Problem • Application needs to manipulate a hierarchical
collection of "primitive" and "composite"
objects. Processing of a primitive object is
handled one way, and processing of a
composite object is handled differently. Having
to query the "type" of each object before
attempting to process it is not desirable.

25
Components
Composite Pattern consists of following
objects:
• Base Component – Base component is
the interface for all objects in the
composition, client program uses base
component to work with the objects in
the composition. It can be an interface or
an abstract class with some methods
common to all the objects.
• Leaf – Defines the behaviour for the
elements in the composition. It is the
building block for the composition and
implements base component. It doesn’t
have references to other Components.
• Composite – It consists of leaf elements
and implements the operations in base
component.

26
Example

27
28
29
30
31
32
33
34
35
36
Consequences
• Makes the client simple

• Easier to add new kinds of components

37
State

Intent • Allow an object to alter its behavior when its


internal state changes. The object will appear
to change its class.

Problem • A monolithic object's behavior is a function of


its state, and it must change its behavior at run-
time depending on that state.

1
Solution

2
Example

3
4
5
6
7
Consequences
• Localizes the state specific behavior

• Makes state transitions explicit

8
Motivation: Strategy

• Quick sort
• Merge sort
• Insertion sort
• Bubble sort
• Radix sort
• Heap sort
• Bucket sort
• ..

9
Strategy

Intent • Define a family of algorithms, encapsulate each


one, and make them interchangeable. Strategy
lets the algorithm vary independently from the
clients that use it.

Problem • Capture the abstraction in an interface, bury


implementation details in derived classes.

10
Solution

11
12
13
14
15
16
17
Consequences
• Families of related algorithms

• Eliminate conditional statements

• Client must be aware of different strategies

18
Motivation: Observer

19
Observer

Intent • Define a one-to-many dependency between


objects so that when one object changes state,
all its dependents are notified and updated
automatically.

Problem • Encapsulate the core (or common or engine)


components in a Subject abstraction, and the
variable (or optional or user interface)
components in an Observer hierarchy.

20
Solution

21
22
23
Consequences
• Decoupling subject and observer

• Support broadcast communication

24
Many observers, many subjects

25
26
27
28
Mediator

29
30
31
32
33
34
35
36
37
38
Template

Intent • Template Method is a behavioral design


pattern that defines the skeleton of an
algorithm in the superclass but lets subclasses
override specific steps of the algorithm without
changing its structure.
Solution • The Template Method lets you turn a
monolithic algorithm into a series of individual
steps which can be easily extended by
subclasses while keeping intact the structure
defined in a superclass.

39
40
41
42
43
44
45
Command

Intent • Command is a behavioral design pattern that


turns a request into a stand-alone object that
contains all information about the request. This
transformation lets you parameterize methods
with different requests, delay or queue a
request’s execution, and support undoable
operations.
Solution • The Command pattern can turn a specific
method call into a stand-alone object. This
change opens up a lot of interesting uses: you
can pass commands as method arguments,
store them inside other objects, switch linked
commands at runtime, etc

46
47
48
49
50
51
52
53

You might also like