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

SAD - Ch10 - Design Patterns

This document discusses system analysis and design patterns. It begins with an introduction to design patterns, explaining that they are commonly used solutions to software design problems, similar to data structures. The document then covers the benefits of design patterns, their origins in architecture, and resources for learning about them. Finally, it describes how design patterns are cataloged, including the template used to describe each pattern and how they are categorized by jurisdiction and characterization.

Uploaded by

LÊ HỮU ĐẠT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

SAD - Ch10 - Design Patterns

This document discusses system analysis and design patterns. It begins with an introduction to design patterns, explaining that they are commonly used solutions to software design problems, similar to data structures. The document then covers the benefits of design patterns, their origins in architecture, and resources for learning about them. Finally, it describes how design patterns are cataloged, including the template used to describe each pattern and how they are categorized by jurisdiction and characterization.

Uploaded by

LÊ HỮU ĐẠT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

System analysis and design

SYSTEM ANALYSIS AND DESIGN


• Nguyen Thanh Binh, Nguyen Quang Vu, Le Viet Truong,
Vo Van Luong, Le Thi Bich Tra, Nguyen Ngoc Huyen Tran
• Faculty of Computer Science

1
System analysis and design

•Chapter 10

Design patterns

2
System analysis and design

Contents

Introduction to Design
Catalog of Design Patterns
Patterns

Some patterns Conclusions

3
System analysis and design

Introduction to Design Patterns

4
System analysis and design

What are Design Patterns?


• Think about the common data structures you learned
• Trees, Stacks, Queues, etc.
• These data structures provide a set of tools on how to organize data
• Probably you implement them slightly differently in different projects
• Main concepts about these data structures, such as
• how to store them
• manipulation algorithms
are well understood
• You can easily communicate these data structures to another software developer
by just stating their name
• Knowing them helps you when you are dealing with data organization in your
software projects
• Better than re-inventing the wheel

5
System analysis and design

What are Design Patterns?


• This is the question:
• Are there common ideas in architectural design of
software that we can learn (and give a name to) so that
• We can communicate them to other software developers
• We can use them in architectural design in a lot of different
contexts (rather than re-inventing the wheel)
• The answer is yes according to E. Gamma, R. Helm,
R. Johnson, J. Vlissides
• They developed a catalog of design patterns that are
common in object-oriented software design

6
System analysis and design

What are Design Patterns?


• Design patterns provide a mechanism for expressing common object-
oriented design structures
• Design patterns identify, name and abstract common themes in
object-oriented design
• Design patterns can be considered micro architectures that contribute
to overall system architecture

7
System analysis and design

Benefits of Design Patterns


• Design patterns
• provide a common vocabulary for designers to communicate, document and
explore design alternatives
• reduce system complexity by naming and defining abstractions that are above
classes and instances
• constitute a reusable base of experience for building software
• act a building blocks for constructing more complex designs
• reduce the learning time for a class library
• provide a target for reorganization and refactoring of class hierarchies

8
System analysis and design

Origins of Design Patterns


• The origins of design patterns are in architecture (not in software architecture)
• Christopher Alexander, a professor of architecture at UC Berkeley, developed a
pattern language for expressing common architectural patterns
• Work of Christopher Alexander inspired the work of Gamma et al.
• In explaining the patterns for architecture, Christopher Alexander says:
“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”
• These comments also apply to software design patterns

9
System analysis and design

Resources for Design Patterns


• “Design Patterns: Abstraction and Reuse of Object-Oriented Design” by E.
Gamma, R. Helm, R. Johnson, J. Vlissides
• Original paper
• Later on same authors published a book which contains an extensive
catalog of design patterns:
• “Design Patterns: Elements of Reusable Object-Oriented Software”, by E. Gamma, R.
Helm, R. Johnson, J. Vlissides, Addison-Wesley, ISBN 0-201-63361-2
• A more recent book
• “Design Patterns Explained”, by A. Shalloway and J. R. Trott, Addison-Wesley, ISBN: 0-
201-71594-5

10
System analysis and design

Catalog of Design Patterns

11
System analysis and design

Cataloging Design Patterns


• Gamma et al. present:
• A way to describe design patterns
• A way to organize design patterns by giving a classification system

• More importantly, in their book on design patterns, the authors give a


catalog of design patterns
• As a typical developer you can use patterns from this catalog
• If you are a good developer, you can contribute to the catalog by discovering and
reporting new patterns

• The template for describing design patterns used by Gamma et al. is given
in the next slide

12
System analysis and design

Design Patterns
• A design pattern consists of three essential parts
1. An abstract description of class or object collaboration and its structure
2. The issue addressed by the design pattern, the circumstances in which it is
applicable
3. Consequences of using the design pattern

• Design patterns are micro-architectures


• They can have several different realizations
• They do not define a complete application or a library
• To be useful they should be applicable to more than one problem

13
System analysis and design

Design Pattern Template


DESIGN PATTERN NAME Jurisdiction Characterization
the name should convey pattern’s essence succinctly used for categorization

Intent
What particular design issue or problem does the design pattern address?
Motivation
A scenario in which the pattern is applicable. This will make it easier to understand the
more abstract description that follows.
Applicability
What are the situations the design pattern can be applied?
Participants
Describe the classes and/or objects participating in the design pattern and their
responsibilities using CRC conventions.
Collaborations
Describe how the participants collaborate to carry out their responsibilities.
Diagram
A class diagram representation of the pattern (extended with pseudo-code).
Consequences
What are the trade-offs and results of using the pattern?
Implementation
What pitfalls, hints, or techniques should one be aware of when implementing the pattern?
Examples
Examples of applications of the pattern in real systems.
See Also
What are the related patterns and what are their differences?
14
System analysis and design

Categorizing Design Patterns


• Two orthogonal criteria can be used to categorize patterns
• Jurisdiction
• Characterization
• Jurisdiction
• Class jurisdiction
• Relationships between base classes and their subclasses, static semantics
• Object jurisdiction
• Relationships between peer objects
• Compound jurisdiction
• Deals with recursive object structures

15
System analysis and design

Characterizing Design Patterns


• Characterization
• Creational patterns
• Deal with initializing and configuring classes or objects
• Structural
• Deal with composition of classes or objects, decoupling interface and implementation of
classes or objects
• Behavioral
• Characterize the ways in which classes or objects interact and distribute responsibility,
deal with dynamic interactions among classes or objects

16
System analysis and design

Characterization
Creational Structural Behavioral

Class Factory Method Adapter(class) Template Method


Bridge(class)

Object Abstract Factory Adapter(object) Chain of Responsibility


Prototype Bridge(object) Command
Jurisdiction Singleton Flyweight Iterator(object)
Facade Mediator
Proxy Momento
Observer
State
Strategy

Compound Builder Composite Interpreter


Decorator Iterator(compound)
Walker
17
System analysis and design

Creational Patterns
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.

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 can create
different representations.
18
System analysis and design

Creational Patterns

Prototype
• Specify the kinds of objects to create using
a prototypical instance and create new
objects by copying this prototype.

Singleton
• Ensure a class only has one instance and
provide a global point of access to it.
19
System analysis and design

Structural Patterns
Adapter
• Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn’t otherwise because of
incompatible interfaces.
Bridge
• Decouple an abstraction from its implementation so that the two can vary
independently.
Composite
• Compose objects into tree structures to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects
uniformly.
Decorator (aka Wrapper)
• Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality
20
System analysis and design

Structural Patterns
Facade (aka Glue)
• Provide a unified interface to a set of interfaces in a subsystem.
Facade defines a higher-level interface that makes the subsystem
easier to use.

Flyweight
• Use sharing to support large numbers of fine-grained object
efficiently.
Proxy
• Provide a surrogate or placeholder for another object to control
access to it
21
System analysis and design

Behavioral Patterns
Chain of Responsibility
• Avoid coupling the sender of a request to its receiver by giving more
than one object a chance to handle the request. Chain the receiving
objects and pass the request along the chain until an object handles it.
Command
• Encapsulate a request as an object, thereby letting you parameterize
clients with different requests, queue or log requests, and support
undoable operations.
Iterator
• Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.

22
System analysis and design

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
Observer
• Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updates
accordingly.
23
System analysis and design

Behavioral Patterns
State
• Allow an object to alter its behavior when its internal state changes. The object will
appear to change its class.

Strategy
• Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.

Template Method
• Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an algorithm without
changing the algorithm’s structure

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.
24
System analysis and design

Some patterns
Factory Method
Observer

25
System analysis and design

Factory Method
• Factory Method is a creational design pattern that provides an
interface for creating objects in a superclass but allows
subclasses to alter the type of objects that will be created.

26
System analysis and design

Problem
• Imagine that you’re creating a logistics management
application. The first version of your app can only
handle transportation by trucks, so the bulk of your
code lives inside the Truck class.
• After a while, your app becomes pretty popular. Each
day you receive dozens of requests from sea
transportation companies to incorporate sea logistics
into the app.
• Great news, right? But how about the code? At
present, most of your code is coupled to the Truck
class. Adding Ships into the app would require making
changes to the entire codebase. Moreover, if later you
decide to add another type of transportation to the
app, you will probably need to make all of these
changes again.
• As a result, you will end up with pretty nasty code,
riddled with conditionals that switch the app’s
behavior depending on the class of transportation
objects.

27
System analysis and design

Solution
• The Factory Method pattern suggests that you
replace direct object construction calls (using
the new operator) with calls to a special
factory method. Don’t worry: the objects are
still created via the new operator, but it’s
being called from within the factory method.
Objects returned by a factory method are
often referred to as products.
• There’s a slight limitation though:
subclasses may return different types of
products only if these products have a
common base class or interface. Also, the
factory method in the base class should
have its return type declared as this
interface.
28
System analysis and design

Structure
1. The Product declares the
interface, which is common to all
objects that can be produced by
the creator and its subclasses.
2. Concrete Products are different
implementations of the product
interface.
3. The Creator class declares the
factory method that returns new
product objects. It’s important that
the return type of this method
matches the product interface.
4. Concrete Creators override the
base factory method, so it returns
a different type of product.
29
System analysis and design

Pseudocode
• This example illustrates how the Factory
Method can be used for creating cross-
platform UI elements without coupling
the client code to concrete UI classes.
• The base dialog class uses different UI
elements to render its window. Under
various operating systems, these elements
may look a little bit different, but they
should still behave consistently. A button in
Windows is still a button in Linux.
• When the factory method comes into play,
you don’t need to rewrite the logic of the
dialog for each operating system.
Java Code: https://refactoring.guru/design-patterns/factory-method/java/example
30
System analysis and design

Applicability
• Use the Factory Method when you don’t know beforehand the exact
types and dependencies of the objects your code should work with.
• Use the Factory Method when you want to provide users of your
library or framework with a way to extend its internal components.
• Use the Factory Method when you want to save system resources by
reusing existing objects instead of rebuilding them each time.

31
System analysis and design

How to Implement
1. Make all products follow the same interface. This interface should declare methods
that make sense in every product.
2. Add an empty factory method inside the creator class. The return type of the method
should match the common product interface.
3. In the creator’s code find all references to product constructors. One by one, replace
them with calls to the factory method, while extracting the product creation code into
the factory method.
4. Now, create a set of creator subclasses for each type of product listed in the factory
method. Override the factory method in the subclasses and extract the appropriate
bits of construction code from the base method.
5. If there are too many product types and it doesn’t make sense to create subclasses for
all of them, you can reuse the control parameter from the base class in subclasses.
6. If, after all of the extractions, the base factory method has become empty, you can
make it abstract. If there’s something left, you can make it a default behavior of the
method.

32
System analysis and design

Observer
• Observer is a behavioral
design pattern that lets you
define a subscription
mechanism to notify multiple
objects about any events
that happen to the object
they’re observing.

33
System analysis and design

Problem
• Imagine that you have two types of objects: a
Customer and a Store. The customer is very
interested in a particular brand of product (say,
it’s a new model of the iPhone) which should
become available in the store very soon.
• The customer could visit the store every day and
check product availability. But while the product
is still en route, most of these trips would be
pointless.
• On the other hand, the store could send tons of
emails (which might be considered spam) to all
customers each time a new product becomes
available. This would save some customers from
endless trips to the store. At the same time, it’d
upset other customers who aren’t interested in
new products.
• It looks like we’ve got a conflict. Either the
customer wastes time checking product
availability or the store wastes resources
notifying the wrong customers.

34
System analysis and design

Solution
• The object that has some interesting state
is often called subject, but since it’s also
going to notify other objects about the
changes to its state, we’ll call it publisher.
All other objects that want to track
changes to the publisher’s state are
called subscribers.
• The Observer pattern suggests that you
add a subscription mechanism to the
publisher class so individual objects can
subscribe to or unsubscribe from a stream
of events coming from that publisher.

35
System analysis and design

Solution (cont)
• Publisher notifies subscribers by calling
the specific notification method on their
objects.

36
System analysis and design

Structure
1.The Publisher issues events of interest to
other objects.
2.When a new event happens, the publisher
goes over the subscription list and calls the
notification method declared in the
subscriber interface on each subscriber
object
3. The Subscriber interface declares the
notification interface.
4.Concrete Subscribers perform some
actions in response to notifications issued by
the publisher.
5.Usually, subscribers need some contextual
information to handle the update correctly.
6.The Client creates publisher and
subscriber objects separately and then
registers subscribers for publisher updates.

37
System analysis and design

Pseudocode
• In this example,
the Observer pattern lets
the text editor object notify
other service objects about
changes in its state.
Java code: https://refactoring.guru/design-patterns/observer/java/example

38
System analysis and design

Applicability
• Use the Observer pattern when changes to the state of one
object may require changing other objects, and the actual set of
objects is unknown beforehand or changes dynamically.
• Use the pattern when some objects in your app must observe
others, but only for a limited time or in specific cases.

39
System analysis and design

How to Implement
1. Look over your business logic and try to break it down into two parts: the core functionality,
independent from other code, will act as the publisher; the rest will turn into a set of subscriber
classes.
2. Declare the subscriber interface. At a bare minimum, it should declare a single update method.
3. Declare the publisher interface and describe a pair of methods for adding a subscriber object to and
removing it from the list. Remember that publishers must work with subscribers only via the
subscriber interface.
4. Decide where to put the actual subscription list and the implementation of subscription methods.
Usually, this code looks the same for all types of publishers, so the obvious place to put it is in an
abstract class derived directly from the publisher interface. Concrete publishers extend that class,
inheriting the subscription behavior.
5. Create concrete publisher classes. Each time something important happens inside a publisher, it
must notify all its subscribers.
6. Implement the update notification methods in concrete subscriber classes. Most subscribers would
need some context data about the event. It can be passed as an argument of the notification
method.
7. The client must create all necessary subscribers and register them with proper publishers.

40
System analysis and design

Conclusions

41
System analysis and design

Conclusions
• Patterns enable widespread reuse of software architecture
• Patterns explicitly capture knowledge that experienced developers already
understand implicitly
• Pattern descriptions explicitly record engineering trade-offs and design alternatives
• The contexts where patterns apply and do not apply must be carefully documented

• Patterns improve communication within and across software development


teams
• Patterns facilitate training of new developers
• Pattern names should be chosen carefully and used consistently
• Successful pattern descriptions capture both structure and behavior

42
System analysis and design

Conclusions
• Useful patterns arise from practical experience
• Pattern authors should be directly involved with application developers and domain
experts
• Pattern descriptions should contain concrete examples
• Patterns are validated by experience rather than by testing
• Everything should not be recast as a pattern
• The focus should be on developing patterns that are strategic to the domain and
reusing existing tactical patterns
• Integrating patterns into a software development process is a human-
intensive activity
• Rewards should be institutionalized for developing patterns
• Patterns can be considered deliverables such as code

43
System analysis and design

Conclusions
• Patterns help to transcend “programming language centric”
viewpoints
• However, implementing patterns efficiently requires careful selection of
language features
• Managing expectations is crucial to using patterns effectively
• Using patterns does not guarantee flexible and efficient software
• Patterns may lead developers to think they know more about the solution to
a problem than they actually do

44

You might also like