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

Week 7 Design Patterns1a

The document discusses design patterns, including their purpose, advantages, and classification. It describes the Gang of Four's (GOF) catalog of 23 patterns, which are divided into creational, structural, and behavioral categories. Creational patterns deal with object creation, structural patterns describe object relationships and connections, and behavioral patterns focus on object interaction and responsibility distribution. Examples are provided for each category, including the Singleton, Builder, and Strategy patterns. The key elements of patterns like context, problem, solution, and consequences are also outlined.

Uploaded by

Mobina AbdulRauf
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Week 7 Design Patterns1a

The document discusses design patterns, including their purpose, advantages, and classification. It describes the Gang of Four's (GOF) catalog of 23 patterns, which are divided into creational, structural, and behavioral categories. Creational patterns deal with object creation, structural patterns describe object relationships and connections, and behavioral patterns focus on object interaction and responsibility distribution. Examples are provided for each category, including the Singleton, Builder, and Strategy patterns. The key elements of patterns like context, problem, solution, and consequences are also outlined.

Uploaded by

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

DESIGN PATTERNS

DR. KHURAM SHAHZAD

1
LEARNING OBJECTIVES

 Upon completion of this course, you will be able to:


(a) explain design patterns commonly applied to interactive applications,
(b) use a foundation for more complex software applications,
(c) identify problematic software designs by referencing a catalogue of
code smells.
(d) redesign an application to use design patterns.

2
INTRODUCTION TO PATTERNS
 Solution to commonly occurring or recurring aspects of design
problems
 Allows you to use previously outlined solutions that expert developers
have used
 A pattern is the outline of a reusable solution to a general problem
encountered in a particular context
 Object oriented design and not code in a programming language
 Represented abstractly, explained with examples
 A good pattern should
 Be as general as possible
3

 Contain a solution that has been proven to effectively solve the problem in
the indicated context.
INTRODUCTION TO PATTERNS

 Abstract design is mapped to a concrete problem


 Various kinds of design pattern:
 Creational, structural, behavioral
 Many of them have been systematically documented for all
software developers to use
 Studying patterns is an effective way to learn from the
experience of others
4
ADVANTAGES

 Design patterns are already been proven by experts


 They help create a design vocabulary
 Studying patterns is an effective way to learn from the
experience of others

5
DESCRIBING A PATTERN
 Specify the generic problem that is to be solved
 Which design pattern to use to solve a software design
problem, especially as many design patterns exist?
 Motivate the design pattern solution with the help of an
example
 Provide the structure for the pattern
 Discuss the collaboration between the classes
 Discuss other issues related to the pattern such as trade offs
and implementation techniques 6
PATTERN BY GANG OF FOUR (GOF)

Gang of Four’s pattern


catalog contains 23 patterns

3 x different categories:
• creational patterns
• structural patterns
• behavioral patterns

7
GOF DESIGN PATTERNS
CLASSIFICATION
 Creational
 Concern the process of object creation
 Structural
 Deal with the composition of classes or objects
 Behavioral
 Characterize the ways in which classes or objects interact
and distribute responsibility

8
PATTERN DESCRIPTION TEMPLATE
PROVIDED BY GOF

 Pattern name, and its classification


 Intent, motivation, applicability.
 Structure, participants, collaboration.
 Consequences, implementation, sample code
 Known uses
 Related pattern

9
CREATIONAL DESIGN PATTERN

 Creational patterns deal with the creation of new objects


 Creational patterns depend on the programming language
being used
 Different ways of creating objects will greatly influence how
a problem is solved

10
EXAMPLES OF CREATIONAL PATTERN

 Abstract Factory

 Provide an interface for creating families of related or dependent objects without specifying their concrete
classes.
 Builder

 Separate the construction of a complex object from its representation so that the same construction
process can create different representations.
 Factory Method

 Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory
Method lets a class defer instantiation to subclasses.
 Prototype

 Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this
prototype.
11
 Singleton

 Ensure a class only has one instance, and provide a global point of access to it.
STRUCTURAL DESIGN PATTERN

 Describe how objects are connected to each other


 Different ways to structure objects depending on the
relationship between them
 Show how subclasses and classes interact through inheritance

 Each structural pattern determines the various suitable


relationships among the objects

12
GOF STRUCTURAL PATTERNS

 Adapter Convert the interface of a class into another interface clients


expect.
 Bridge Decouple an abstraction from its implementation so that the two
can vary independently.
 Composite Compose objects into tree structures
 Decorator Compose objects into tree structures
 Decorator Attach additional responsibilities to an object dynamically.
 Facade Provide a unified interface to a set of interfaces in a subsystem.
 Flyweight Use sharing to support large numbers of fine-grained objects
efficiently.
 Proxy Provide a surrogate or placeholder for another object to control13
access to it.
BEHAVIORAL DESIGN PATTERN

Focus on how objects distribute work


Describe how each object does a single
cohesive function
Behavioral patterns also focus on how
independent objects work towards a common
goal
14
GOF BEHAVIORAL PATTERNS

 Template Method
 Lets certain steps in a super class be defined by sub class.
 Strategy
 encapsulate family of algorithm and make them interchangeable.
 Iterator
 Provide a way to access the elements of an aggregate object sequentially
without exposing its underlying representation.
 Observer
 when one object changes state, all its dependents are notified and updated
automatically.
 State
15
 Allow an object to alter its behavior when its internal state changes. The
object will appear to change its class
GOF BEHAVIORAL PATTERNS
 Mediator
 Define an object that encapsulates how a set of objects interact. Mediator promotes loose
coupling by keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.
 Memento
 Without violating encapsulation, capture and externalize an object's internal state so that the
object can be restored to this state later.
 . Visitor

 Represent an operation to be performed on the elements of an object structure. Visitor lets you
define a new operation without changing the classes of the elements on which it operates.
 Chain of Responsibility
 Avoid coupling the sender of a request to its receiver by giving more than one object a chance
16 to
handle the request. Chain the receiving objects and pass the request along the chain until an
object handles it.
GOF BEHAVIORAL PATTERNS

 Command
 Encapsulate a request as an object, thereby letting you
parameterize clients with different requests, queue or log
requests, and support undoable operations.
 Interpreter
 Given a language, define a representation for its grammar along
with an interpreter that uses the representation to interpret
sentences in the language.

17
18
SCOPE OF PATTERNS

 Scope specifies whether the pattern applies primarily to


classes or to objects.
 Class patterns deal with relationships between classes and
their subclasses.
 These relationships are established through inheritance, so they
are static—fixed at compile-time.
 Object patterns deal with object relationships, which can be
changed at run-time and are more dynamic.

19
GOF ESSENTIAL ELEMENTS OF
PATTERNS
 Pattern Name
 Having a concise, meaningful name for a pattern improves
communication among developers
 Problem
 What is the problem and context where we would use this pattern?
 Solution
 A description of the elements that make up the design pattern
 Emphasizes their relationships, responsibilities and collaborations
 Not a concrete design or implementation; rather an abstract
description
 Consequences 20

 The pros and cons of using the pattern


PATTERN DESCRIPTION (TEXTBOOK)
Context:
 The general situation in which the pattern applies
Problem:
 A short sentence or two raising the main difficulty.
Forces:
 The issues or concerns to consider when solving the problem
Solution:
 The recommended way to solve the problem in the given context.
 ‘to balance the forces’
Antipatterns: (Optional)
 Solutions that are inferior or do not work in this context.
Related patterns: (Optional)
 Patterns that are similar to this pattern.
21
References:
 Who developed or inspired the pattern.
CREATIONAL DESIGN PATTERNS

22
SINGLETON DESIGN PATTERN
 A singleton is a creational pattern, which describes a way to create an
object
 Context:
 It is very common to find classes for which only one instance should exist
(singleton)
 Problem:
 How do you ensure that it is never possible to create more than one
instance of a singleton class?
 Forces:
 The use of a public constructor cannot guarantee that no more than one
instance will be created.
 The singleton instance must also be accessible to all classes that require it 23
EXAMPLE
Enforces one and only one object of a singleton class

24
SOLUTION

25
EXAMPLE

Public class notSingleton


{
//Public Constructor
Public notSingleton()
{
..
}
}
26
EXAMPLE CONTD…

ExampleSingleton

-
instance:ExampleSingleton
-ExampleSingleton()
+getInstance():ExampleSingleto
n
+showmessage():void

27
SOME OTHER KEY FACTS

 It can be a powerful technique on its own, or in combination with other


design patterns. 
 Trade-offs to the Singleton design principle
 If multiple computing threads running, there could be issues caused by the
threads trying to access the shared single object
 In real use, there may be variations of how Singleton is realized, as design
patterns are defined by purpose and not exact code.

28
FACTORY METHODS PATTERN

 It is a type of creational pattern


 You can make out from the name factory itself its meant to
construct and create something
 Define an interface for creating an object, but let subclasses
decide which class to instantiate.
 Factory Method lets a class defer instantiation to subclasses
 To understand Factory Method patterns, we must first
understand factory objects

29
FACTORY METHODS PATTERN

 Factory Object

 Operates like a factory in the real world, and creates


objects.
 Makes software easier to maintain and change, because
object creation happens in the factories
 The methods that use these Factories can then focus on
other behavior

30
FACTORY METHODS PATTERN

Samsung Galaxy S20 iPhone12

31
FACTORY METHODS PATTERN
Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone = null; // create smartphone object
If (smartphoneType.equals(“samsung”))
{ Concrete instantiation is
smartphone = new samsungGalaxyS20(); indicated with the operator
Huawei P30 Pro
} “new”
else if (smartphoneType.equals(“iphone”))
{
smartphone = new iphone12();
}
// prepare smartphone
smartphone.embellish()
smartphone.polish()
smartphone.packaging()
return smartphone; 32

} Google Pixel 4A
FACTORY METHODS PATTERN
Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone = null; // create smartphone object
If (smartphoneType.equals(“samsung”))
{
smartphone = new samsungGalaxyS20(); Concrete instantiation is
}
else if (smartphoneType.equals(“iPhone”)) indicated with the operator
{ “new” Huawei phone
smartphone = new iPhone12();
else if (smartphoneType.equals(“Huawei”))
{
smartphone = new Huaweip30pro();
}
else if (smartphoneType.equals(“Google”))
{
smartphone = new GooglePixel4A();
}
// prepare smartphone
smartphone.embellish()
smartphone.polish()
Generic functions applied to all
smartphone.packaging() smartphone types Google Pixel 4A
return smartphone; 33
}
FACTORY METHODS PATTERN

34
FACTORY METHODS PATTERN

public class smartphoneFactory


{ public Smartphone createsmartphone(String smartphoneType)
{
Smartphone smartphone = null; // create smartphone object
If (smartphoneType.equals(“samsung”))
{
smartphone = new samsungGalaxyS20();
}
else if (smartphoneType.equals(“iPhone”))
{
smartphone = new iPhone12();
}
return smartphone;
} 35

}
FACTORY METHODS PATTERN
public class SmartphoneStore {
private SmartphoneFactory factory;
 Public SmartphoneStore(smartphoneFactory factory)
{ // require a smartphoneFactory object to
be passed to this constructor:
this.factory = factory;
}
Public Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone;
smartphone = factory.createsmartphone(smartphoneType); //use the create method in
//prepare the smartphone the factory
smartphone.embellish();
smartphone.polish();
smartphone.package();
return smartphone; 36

}
}
FACTORY METHODS PATTERN

37
FACTORY METHODS PATTERN

The factory method design intent is to define an interface for creating objects, but let the
sub-classes decide which class to instantiate

public abstract class SmartphoneStore


{
public Smartphone ordersmartphone(String smartphoneType)
{
Smartphone smartphone;
// now creating a smartphone is a method in the class Basic Smart phones
smartphone = createsmartphone(smartphoneType);
smartphone.sharpen();
smartphone.polish();
smartphone.package();
return smartphone;
}
38
abstract Smartphone createsmartphone(String type);
} Professional Smart phones
FACTORY METHODS PATTERN
public BasicSmartphoneStore extends smartphoneStore
{
smartphone createsmartphone(String smartphoneType) //up to any subclass of smartphoneStore to define this method
{
if (smartphoneType.equals(“samsung”))
{
return new BasicSamsungPhone();
}
else if (smartphoneType.equals(“iPhone”))
{
return new BasiciPhone();
} //.. more types
else return null;
} 39

}
FACTORY METHODS PATTERN

smartphone smartphoneStore

ordersmartphone()
createsmartphone()

BasicSamsungPhone BasicSmartphoneStore

createsmartphone()

40
FACTORY METHODS PATTERN

41

https://www.youtube.com/watch?v=pt1IbV1aSZ4
SUMMARY

 A factory is generally a method or object that allows you to create other objects
 Act of object creation, usually with the new keyword in Java is called concrete
instantiation
 A factory object may be a useful tool if many parts of the software want to create
the same objects
 Factory method pattern is a little bit different. Instead of using another object to
create objects, we separate out object creation into another method, a Factory
method
 By separating the actual object creation from other behavior using factories, the
code becomes cleaner to read and easier to maintain or change

42
PROTOTYPE DESIGN PATTERN

 They fall into creational category


 It gives us a way to create new objects from the existing
instance of the object.
 In one sentence we clone the existing object with its data.
 By cloning any changes made to the cloned objct does not
affect the original object.

43
PROTOTYPE DESIGN PATTERN

 A problem
 In a graphical; editor, by clicking on an object one can obtain
the copy of an original object. Obtaining the copy of an
existing object is a common design problem in online
composition
 We can provide a design solution to solve this problem, and
reuse this design whenever similar solution arises.

44
PROTOTYPE PATTERN

Client proto ShapePrototype


Operation()
clone()

proto->clone()

CirclePrototype RectanglePrototype

clone() clone()

45

Copy self Copy self


PROTOTYPE PATTERN

Client proto Prototype


Operation()
clone()

proto->clone()

ConcretePrototype I ConcretePrototype II

clone() clone()

46

Copy self Copy self


/* Polymorphism Example: InfoBrother */  
#include <iostream> using namespace std;  
class Shape //base class.
{
protected:
int width, height;  
public:
Shape( int a=0, int b=0) //Constructor.
{ width = a; height = b; }  
virtual int clone() //Simple Function to copy the result.
{ cout << "Shape class area | Base Class | :" <<endl; return 0; }
};  

class Rectangle:public Shape //Derived Class from the Class shape.


{
public:
Rectangle( int a=0, int b=0):Shape(a, b)
{ } //constructor.
int area () //Simple function to display result.
{ cout << "Rectangle class area | Derived Class | :" <<endl; return (width * height); }
};    
class Triangle: public Shape //Derived Class from class Shape.
{
public:
Triangle( int a=0, int b=0):Shape(a, b)
{ } //Constructor.
int area () //Simple function to display result.
{ cout << "Triangle class area | Derived Class | :" <<endl; return (width * height / 2); }
};    
int main( )
{ Shape *shape; //pointer Object of type shape.
Rectangle rec(10,7); //Rectangle Object.
Triangle tri(10,5); //Triangle Object.    
shape = &rec; // store the address of Rectangle 47
shape->area(); // call rectangle area using this pointer.  
shape = &tri; // store the address of Triangle shape->area(); // call triangle area using this pointer.
return 0; }
CREATIONAL DESIGN PATTERN

 Reference: University of Alberta Design pattern course notes

(Available on LMS in books folder)

48
STRUCTURAL DESIGN PATTERNS

49
ADAPTOR METHOD (STRUCTURAL)

 You are building a collection class hierarchy for


collections such as FIFO, LIFO
 You find that there is an existing class stack which can
be used for providing LIFO collection
 How do we adapt the existing class to the new
interface of collection classes?

50
SOLUTION

Client Collection Stack

Insert () Push()
Fetch () Pop()

FIFO LIFO

Insert () Insert ()
Fetch () Fetch ()
51

Push()
ADAPTER

Client Target Adaptee

Request () specificReq()

Adapter

Request ()

52

specificRequest ()
ADAPTER

Client Target Adaptee

Request () specificReq()

Adaptee

Adapter

Request ()

53

Adaptee->specificRequest ()
FACADE PATTERN

 Context:
 Often, an application contains several complex packages.
 A programmer working with such packages has to manipulate many different
classes
 Problem:
 How do you simplify the view that programmers have of a complex package?
 Forces:
 It is hard for a programmer to understand and use an entire subsystem
 If several different application classes call methods of the complex package,
then any modifications made to the package will necessitate a complete review
of all these classes. 54
FACADE
 Solution:

55
STRUCTURAL DESIGN PATTERN

 Reference:
 https://freevideolectures.com/course/2318/software-engineering/15
 Object-Oriented Software Engineering: Practical Software Development using UML
and Java by Timothy C. Lethbridge and Robert Laganière, 2004.

56
BEHAVIORAL DESIGN PATTERNS

57
STATE DESIGN PATTERN (BEHAVIORAL)

 This is a behavioral pattern as it defines a manner for


controlling communication between classes or entities.
 Allow an object to alter its behavior when its internal state
changes.
 The object will appear to change its class.
 Allow an object to change its state at runtime.

58
STATE PATTERN (EXAMPLE)
Vending machines have states based on the inventory, amount of currency
deposited, the ability to make change, the item selected, etc.
When currency is deposited and a selection is made, a vending machine
will either deliver a product and no change, deliver a product and change,
deliver no product due to insufficient currency on deposit, or deliver no
product due to inventory depletion.

59
STATE PATTERN (EXAMPLE)

• Machine would dispense a chocolate bar


based on your selection

• You decided to press the eject money


button and no longer buy the chocolate

• Machine could be out of chocolate bars,


and could notify you of this.

60
STATE PATTERN

61
STATE PATTERN

62
STATE PATTERN

 3 x different states of vending machine


 Machine is in an idle state
 When the dollar is inserted, the state of the machine changes, and
could either dispense a product or return the money upon receiving an
eject money request
 Machine could be out of stock

63
STATE PATTERN

64
STATE PATTERN

65
STATE PATTERN

66
STATE PATTERN

67
STATE PATTERN

68
STATE PATTERN

69
STATE PATTERN

70
STATE PATTERN

71
STATE PATTERN

72
STATE PATTERN

73
STATE PATTERN

74
STATE PATTERN (SUMMARY)

 State pattern is a solution to the problem of how to make behavior depend


on state.
 Define a “context” class to present a single interface to the outside world.
 Define a State abstract base class.
 Represent the different “states” of the state machine as derived classes of
the State base class.
 Define state-specific behavior in the appropriate State derived classes.
 Maintain a pointer to the current “state” in the “context” class.
 To change the state of the state machine, change the current
“state” pointer. 75
STATE PATTERN

 Reference: University of Alberta Design pattern course notes

(Available on LMS in books folder)

76
OBSERVER PATTERN

 Context:
 When an association is created between two classes, the code for the
classes becomes inseparable.
 If you want to reuse one class, then you also have to reuse the other.
 Problem:
 How do you reduce the interconnection between classes, especially
between classes that belong to different modules or subsystems?
 Forces:
 You want to maximize the flexibility of the system to the greatest extent
possible

77
OBSERVER PATTERN
 Solution:

78
OBSERVER PATTERN

 Antipatterns:
 Connect an observer directly to an observable so that they both have references to each
other.
 Make the observers subclasses of the observable.

79
OBSERVER PATTEN

 Reference:
 Object-Oriented Software Engineering: Practical Software Development using UML
and Java by Timothy C. Lethbridge and Robert Laganière, 2004.

80
COMMAND DESIGN PATTERN

 They fall into behavioral category


 Command Pattern allows a request to exist as an object
 Intent
 encapsulate a request in an object
 allows the parameterization of clients with different requests
 allows saving the requests in a queue

81
COMMAND PATTERN

82
COMMAND PATTERN

83
COMMAND PATTERN

84
COMMAND PATTERN

85
 The classes participating in the pattern are:
 Command
 declares an interface for executing an operation;

 ConcreteCommand
 extends the Command interface, implementing the Execute method by invoking the
corresponding operations on Receiver. It defines a link between the Receiver and the
action.
 Client - creates a ConcreteCommand object and sets its receiver;
 Invoker - asks the command to carry out the request;

 Receiver - knows how to perform the operations;


86
COMMAND PATTERN

 The Client asks for a command to be executed.


 The Invoker takes the command, encapsulates it and places it
in a queue, in case there is something else to do first, and
 the ConcreteCommand that is in charge of the requested
command, sending its result to the Receiver.

87
ABSTRACTION-OCCURRENCE PATTERN

 Context:
 Often in a domain model you find a set of related objects (occurrences).
 The members of such a set share common information
 but also differ from each other in important ways.

 Problem:
 What is the best way to represent such sets of occurrences in a class
diagram?
  Forces:
 You want to represent the members of each set of occurrences without
duplicating the common information
88
ABSTRACTION-OCCURRENCE

 Solution:

89
ABSTRACTION-OCCURRENCE

 Antipatterns:

90
ABSTRACTION-OCCURRENCE

 Square variant

91
THE GENERAL HIERARCHY PATTERN
 Context:
 Objects in a hierarchy can have one or more objects above them
(superiors),
 and one or more objects below them (subordinates).

 Some objects cannot have any subordinates


 Problem:
 How do you represent a hierarchy of objects, in which some objects
cannot have subordinates?
 Forces:
 You want a flexible way of representing the hierarchy
92
 that prevents certain objects from having subordinates

 All the objects have many common properties and operations


GENERAL HIERARCHY

 Solution:

93
GENERAL HIERARCHY

 Solution:

94
GENERAL HIERARCHY

 Antipattern:

95
THE PLAYER-ROLE PATTERN

 Context:
 A role is a particular set of properties associated with an object in a particular context.
 An object may play different roles in different contexts.

 Problem:
 How do you best model players and roles so that a player can change roles or possess multiple
roles?

96
PLAYER-ROLE

 Forces:
 It is desirable to improve encapsulation by capturing the
information associated with each separate role in a class.
 You want to avoid multiple inheritance.
 You cannot allow an instance to change class
 Solution:

97
PLAYER-ROLE

 Example 1:

98
PLAYER-ROLE

 Example 2:

99
PLAYER-ROLE

 Antipatterns:

 Merge all the properties and behaviours into a single «Player» class and not have
«Role» classes at all.
 Create roles as subclasses of the «Player» class.

100
THE SINGLETON PATTERN

 Context:
 It is very common to find classes for which only one instance should exist (singleton)

 Problem:
 How do you ensure that it is never possible to create more than one instance of a singleton
class?
 Forces:
 The use of a public constructor cannot guarantee that no more than one instance will be created.
 The singleton instance must also be accessible to all classes that require it

101
SINGLETON

 Solution:

102
THE OBSERVER PATTERN

 Context:
 When an association is created between two classes, the code for the classes becomes
inseparable.
 If you want to reuse one class, then you also have to reuse the other.
 Problem:
 How do you reduce the interconnection between classes, especially between classes that belong
to different modules or subsystems?
 Forces:
 You want to maximize the flexibility of the system to the greatest extent possible

103
OBSERVER

 Solution:

104
OBSERVER

 Antipatterns:
 Connect an observer directly to an observable so that they both have references to each
other.
 Make the observers subclasses of the observable.

105
6.7 THE DELEGATION PATTERN

 Context:
 You are designing a method in a class
 You realize that another class has a method which provides the required service
 Inheritance is not appropriate
 E.g. because the isa rule does not apply

 Problem:
 How can you most effectively make use of a method that already exists in the other class?
 Forces:
 You want to minimize development cost by reusing methods

106
DELEGATION

 Solution:

107
DELEGATION
Example:

108
DELEGATION

 Antipatterns
 Overuse generalization and inherit the method that is to be reused
 Instead of creating a single method in the «Delegator» that does nothing other than call
a method in the «Delegate
 consider having many different methods in the «Delegator» call the delegate’s method

 Access non-neighboring classes


return specificFlight.regularFlight.flightNumber();

return getRegularFlight().flightNumber();
109
6.8 THE ADAPTER PATTERN

 Context:
 You are building an inheritance hierarchy and want to incorporate it into an
existing class.
 The reused class is also often already part of its own inheritance hierarchy.
 Problem:
 How to obtain the power of polymorphism when reusing a class whose methods
 have the same function
 but not the same signature
as the other methods in the hierarchy?
 Forces:
 You do not have access to multiple inheritance or you do not want to use it.

110
ADAPTER

 Solution:

111
ADAPTER

 Example:

112
6.9 THE FAÇADE PATTERN

 Context:
 Often, an application contains several complex packages.
 A programmer working with such packages has to manipulate many different
classes
 Problem:
 How do you simplify the view that programmers have of a complex package?
 Forces:
 It is hard for a programmer to understand and use an entire subsystem
 If several different application classes call methods of the complex package, then
any modifications made to the package will necessitate a complete review of all
these classes.

113
FAÇADE

 Solution:

114
6.10 THE IMMUTABLE PATTERN

 Context:
 An immutable object is an object that has a state that never changes after creation
 Problem:
 How do you create a class whose instances are immutable?
 Forces:
 There must be no loopholes that would allow ‘illegal’ modification of an immutable object
 Solution:
 Ensure that the constructor of the immutable class is the only place where the values of
instance variables are set or modified.
 Instance methods which access properties must not have side effects.
 If a method that would otherwise modify an instance variable is required, then it has to
return a new instance of the class.

115
6.11 THE READ-ONLY INTERFACE PATTERN

 Context:
 You sometimes want certain privileged classes to be able to modify
attributes of objects that are otherwise immutable
 Problem:
 How do you create a situation where some classes see a class as read-only
whereas others are able to make modifications?
 Forces:
 Restricting access by using the public, protected and private
keywords is not adequately selective.
 Making access public makes it public for both reading and writing

116
READ-ONLY INTERFACE

 Solution:

117
READ-ONLY INTERFACE

 Example:

118
READ-ONLY INTERFACE

 Antipatterns:
 Make the read-only class a subclass of the «Mutable» class
 Override all methods that modify properties
 such that they throw an exception

119
6.12 THE PROXY PATTERN

 Context:
 Often, it is time-consuming and complicated to create instances of a class
(heavyweight classes).
 There is a time delay and a complex mechanism involved in creating the object in
memory
 Problem:
 How to reduce the need to create instances of a heavyweight class?
 Forces:
 We want all the objects in a domain model to be available for programs to use when
they execute a system’s various responsibilities.
 It is also important for many objects to persist from run to run of the same program

120
PROXY

 Solution:

121
PROXY

 Examples:

122
6.13 THE FACTORY PATTERN

 Context:
 A reusable framework needs to create objecs; however the class of the created objects depends
on the application.
 Problem:
 How do you enable a programmer to add new application-specific class into a system built on
such a framework?
 Forces:
 We want to have the framework create and work with application-specific classes that the
framework does not yet know about.
 Solution:
 The framework delegates the creation of application-specific classes to a specialized class, the
Factory.
 The Factory is a generic interface defined in the framework.
 The factory interface declares a method whose purpose is to create some subclass of a generic
class.

123
THE FACTORY PATTERN

 Solution

124
THE FACTORY PATTERN

 Example

125
6.14 DETAILED EXAMPLE: ENHANCING OCSF
WITH SOME DESIGN PATTERNS

126
THE OBSERVABLE LAYER OF OCSF
(CONTINUED)

127
USING THE OBSERVABLE LAYER
1. Create a class that implements the Observer interface.
2. Register it as an observer of the Observable:

public MessageHandler(Observable client)


{
client.addObserver(this);
...
}
 
3. Define the update method in the new class: 

public void update(Observable obs, Object message)


{
if (message instanceOf SomeClass)
{
// process the message
}
}
  128
6.15 DIFFICULTIES AND RISKS WHEN
CREATING CLASS DIAGRAMS

 Patterns are not a panacea:


 Whenever you see an indication that a pattern should be applied, you might be tempted to
blindly apply the pattern.
 This can lead to unwise design decisions .

 Resolution:
 Always understand in depth the forces that need to be balanced, and when other patterns better
balance the forces.
 Make sure you justify each design decision carefully.

129
DIFFICULTIES AND RISKS WHEN CREATING
CLASS DIAGRAMS

 Developing patterns is hard


 Writing a good pattern takes considerable work.
 A poor pattern can be hard to apply correctly

 Resolution:
 Do not write patterns for others to use until you have considerable experience both in software
design and in the use of patterns.
 Take an in-depth course on patterns.
 Iteratively refine your patterns, and have them peer reviewed at each iteration.

130

You might also like