The document discusses design patterns and provides information about various topics related to design patterns including:
- A catalog of 23 design patterns organized by purpose and scope.
- How design patterns help solve common problems in object-oriented design such as determining object granularity and specifying object interfaces.
- The elements used for describing design patterns such as name, intent, structure, participants, and consequences.
- Organizing design patterns into categories including creational, structural, and behavioral patterns.
What are design principles and how are they different from design patterns?
Why we use design principles?
Some Design principles for an idea.
What are design patterns and their grouping into
Creational Patterns
Structural Patterns
Behavioral Patterns
Conclusion.
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
SVR Technologies providing the course content of C Sharp.net. It was given by our expert Poornima to improve the knowledge of the readers. For more details about other IT courses please visit http://www.svrtechnologies.com
SVR Technologies
Contact: 91- 988 502 2027
info@svrtechnologies.com
http://svrtechnologies.com
OOAD Part A Question with answer and Part B & C questions.
References :
1) Previous University Questions.
2) Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Craig Larman.
3) Google search engine for text and images.
What are design principles and how are they different from design patterns?
Why we use design principles?
Some Design principles for an idea.
What are design patterns and their grouping into
Creational Patterns
Structural Patterns
Behavioral Patterns
Conclusion.
C#.net, C Sharp.Net Online Training Course ContentSVRTechnologies
SVR Technologies providing the course content of C Sharp.net. It was given by our expert Poornima to improve the knowledge of the readers. For more details about other IT courses please visit http://www.svrtechnologies.com
SVR Technologies
Contact: 91- 988 502 2027
info@svrtechnologies.com
http://svrtechnologies.com
OOAD Part A Question with answer and Part B & C questions.
References :
1) Previous University Questions.
2) Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Craig Larman.
3) Google search engine for text and images.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
Immunizing Image Classifiers Against Localized Adversary Attacksgerogepatton
This paper addresses the vulnerability of deep learning models, particularly convolutional neural networks
(CNN)s, to adversarial attacks and presents a proactive training technique designed to counter them. We
introduce a novel volumization algorithm, which transforms 2D images into 3D volumetric representations.
When combined with 3D convolution and deep curriculum learning optimization (CLO), itsignificantly improves
the immunity of models against localized universal attacks by up to 40%. We evaluate our proposed approach
using contemporary CNN architectures and the modified Canadian Institute for Advanced Research (CIFAR-10
and CIFAR-100) and ImageNet Large Scale Visual Recognition Challenge (ILSVRC12) datasets, showcasing
accuracy improvements over previous techniques. The results indicate that the combination of the volumetric
input and curriculum learning holds significant promise for mitigating adversarial attacks without necessitating
adversary training.
3. UNIT-I 3
Syllabus
Sn o Topic Lectures PPT Slides
1 What is Design Pattern? L1 3 – 9
2 Design Patterns in Smalltalk MVC L2 10 – 13
3 Describing Design Patterns L3 14 – 18
4 The catalog of Design Patterns L4 19 – 28
5 Organizing the catalog L5 29 – 30
6 How Design Patterns Solve Design Problems L6 31 – 59
7 How to select Design Patterns L7 60 – 61
8 How to Use a Design Pattern L8 62 – 63
9 Review Unit-I, Online resources L9 64 – 64
UNIT 1
4. UNIT-I 4
WhatisaDesignPattern?
• Each pattern Describes a problem which occurs over and over
againinourenvironment ,andthendescribesthe coreof theproblem.
• Novelists, playwrights and other writers rarely invent new stories.
• Often ideasare reused, suchasthe TragicHero from HamletorMacbeth.
• Designersreusesolutionsalso,preferablythegood ones
• Problems areaddressed withoutrediscovering solutions fromscratch.
L1
5. UNIT-I 5
DesignPatterns
• Design Patterns are the well defined solutions for there occurring
problemsin theapplicationprogramming environment.
• It is atemplate method.
• MainlyusedinObjectOrientedprogramming.
L1
6. Common Problems
Creating a class properly
Instantiating an Object
Interaction between objects
Write loosely coupled code
Write re-usable code
Benefits of Design Patterns
Code Re-usability
High maintenance
Reduced cost
Loosely coupled application
7. UNIT-I 7
DesignPatternElements
1. Pattern Name
Handle used to describe the design problem
Naming a pattern immediately increases our
vocabulary
It makes it easier to think about designs and
communicate them
Finding good names has been one of the hardest
parts of developing our catalog
L1
8. UNIT-I 8
Design Pattern Elements
2. Problem
Describes when to apply the pattern
It explains the problem and its context.
It might describe specific design problems such as how
to represent algorithms as objects.
It may include conditions for the pattern to be
applicable symptoms of an inflexible design or limitation.
L1
9. UNIT-I 9
Design Pattern Elements
3. Solution
The solution describes elements for the design
includes relationships, responsibilities, and
collaborations.
Does not describe a particular concrete designs or
implementations, because a pattern is like a template.
L1
10. UNIT-I 10
DesignPatternElements
4. Consequences
Consequences are the Results and Trade Offs of
applying the Pattern
Critical for design pattern evaluation Often
space and time trade offs
Consequences of a pattern include its impact
of a system’s flexibility, extensibility or
probability
Language strengths and limitations
(Broken into benefits and drawbacks for this discussion)
L1
14. UNIT-I 14
DesignPatternsinSmalltalk MVC
Thebelowdiagramshowsamodelandthreeviews.
Themodelcontainssomedata values, and the views defininga
spreadsheet,histogram,andpiechartdisplay thesedatainvarious
ways.
Themodelcommunicateswithit‘svalues change, and the views
communicatewiththemodeltoaccessthesevalues.
FeatureofMVCisthatviewscanbenested.
Easytomaintainandenhancement.
L2
15. Design Patterns in Smalltalk MVC
A=10%
B=40%
C=30%
D=20%
Application data
A
D
B
C
Relative Percentages
A B C D
X 15 35 35 15
Y 10 40 30 20
Z 10 40 30 20
A B C D
Change notification
Requests, modifications
L2
UNIT-I 15
17. DescribingDesignPatterns
Template
1. Pattern Name and Classification
2. Intent
3. Also Known As
4. Motivation
5. Applicability
6. Structure
7. Participants
8. Collaborations
9. Consequences
10. Implementation
11. Sample Code
12. Known Uses
13. Related Patterns
18. UNIT-I 18
Describing Design Patterns
1.Pattern Name and Classification
It conveys the essence of the pattern succinctly(in a brief and
clearly expressed manner)
A good name is vital, because it will become part of our design
vocabulary.
2.Intent
It answers the following questions,
What does the design pattern do?
What is its rationale(consistent with or based on or using reason)
and intent?
What particular design issue or problem does it address?
L3
19. 3.Also Known As
Other well-known names for the pattern, if any.
4.Motivation
A scenario that illustrates a design problem and how the class
and object structures in the pattern solve the problem.
The scenario will help you to understand the more abstract
description of the pattern that follows.
20. 5.Applicability
What are the situations in which the design patterns can be applied?
What are example of the poor designs that the pattern can address?
How can you recognize these situations?
6.Structure
Graphical representation of the classes in the pattern using a
notation based on the Object Modeling Technique(OMT).
(https://www.geeksforgeeks.org/software-engineering-object-modeling-technique-omt/)
7. Participants
The classes and/or objects participating in the design pattern and
their responsibilities.
1
L3
21. UNIT-I 21
8. Collaborations
How the participants collaborate to carry out their
responsibilities.
9. Consequences(results of an action or situation)
How does the pattern support its objectives?
What are the trade-offs and result of using the
pattern ?
What aspect of the system structure does it let you
vary independently?
10. Implementation
What Pitfalls(a likely mistake or problem in a situation),
Hints, Techniques should be aware of when
implementing the pattern ?
Are there language-specific issues?
L3
22. UNIT-I 22
11.Sample Code
Code fragments that illustrate how you might implement the
pattern in C++ or Smalltalk.
12.Known Uses
Examples of the pattern found in real systems.
We include at least two examples from different domains
13.Related Patterns
What design patterns are closely related to this one? What are the
important differences?
With Which other patterns should this one be used?
L3
23. UNIT-I 23
The Catalog of Design Pattern
1. Abstract Factory: Provide an interface for creating
families of related or dependent objects without
specifying their concrete classes.
2. Adapter: Convert the interface of a class into another
interface clients expect.
3. Bridge: Decouple an abstraction from its implementation
so that two can vary independently.
L4
24. UNIT-I 24
The Catalog of Design Pattern
4. Builder: Separates the construction of the complex object from
its representation so that the same construction process can
createdifferent representations.
5. Chain of Responsibility: Avoid coupling the sender of a request
to it‘s receiver by giving more than one object a chance to
handle the request. Chain the receiving objects and pass the
requestalongthechain untilanobjectshandlesit.
L4
25. UNIT-I 25
The Catalog of Design Pattern
6. Command: Encapsulate a request as an object,
thereby letting parameterize clients with different
request, queue or log requests, and support
undoable operations.
7. Composite: Compose objects into three objects to
represent part-whole hierarchies. Composite lets
clients treat individual objects and compositions
of objects uniformly.
L4
26. UNIT-I 26
The Catalog of Design Pattern
8. Decorator: Attach additional responsibilities to
an object dynamically. Decorators provide a
flexible alternative to sub classing for
extending functionality.
9. Facade: Provide a unified interface to a set of
interfaces in a subsystem's Facade defines a
higher-level interface that makes the
subsystem easier to use.
L4
27. UNIT-I 27
The Catalog of Design Pattern
10. Factory Method: Defines an interface for creating an
object ,but let subclasses decide which class to
instantiate. Factory Method lets a class defer
instantiation to subclasses.
11. Flyweight: Use sharing to support large numbers of
fine- grained objects efficiently.
12. Interpreter: Given a language, defining a representation
of its grammar along with an interpreter that uses the
representation to interpret sentences in the language.
L4
28. UNIT-I 28
TheCatalogofDesignPattern
13. Iterator: Provide a way to access the element of an
aggregate object sequentially without exposing its
underlying representation.
14.Mediator:Defineanobjectthatencapsulatehowa setof
objectsinteract.Mediatorpromotesloose couplingbykeeping
objectsfromreferringtoeach otherexplicitly,andlet‘syouvery
theirinteraction independently.
L4
29. UNIT-I 29
TheCatalogofDesign Pattern
15. Memento: Without violating encapsulation,
capture and externalize an object‘s internal state
so that object can be restored to this state later.
16. Observer: Define a one-to-many dependency
between objects
so that when one object changes state, all
it‘s dependents are notified and updated
automatically.
30. UNIT-I 30
TheCatalogofDesign Pattern
17. Prototype: Specify the kinds of objects to create
using a prototypical instance, and create new objects
by copying this prototype.
18. Proxy: Provide a surrogate or placeholder for another
object to control access to it.
19. Singleton: Ensure a class has only one instance, and
provide a point of access to it.
20. State: Allow an object to alter its behavior when its
internal state changes. the object will appear to change
its class.
L4
31. UNIT-I 31
TheCatalogofDesignPattern
21. Strategy: Define a family of algorithms, encapsulate each
one, and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use it.
22.Template Method: Define the Skelton of an operation,
deferring some steps to subclasses. Template method
subclasses redefine certain steps of an algorithm without
changing the algorithms structure.
23.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.
32. UNIT-I 32
•Two criteria
Purpose: what a pattern does
Creational: The process of object creation
Structural: The composition of classes or objects
Behavioral: Characterize the ways in which classes or
objects interact and distribute responsibility
Scope: whether the pattern applies primarily to
classes or to objects
Organizing the Catalog L5
36. UNIT-I 36
How Design Patterns Solve Design Problems
• FindingAppropriate Objects
– Decomposing a system into objects is the hard part
– Object Oriented Designs often end up with classes
with no counterparts in real world (low-level classes
like arrays)
– Strict modeling of the real world leads to a system
that reflects today‘s realities but not necessarily
tomorrows
– Design patterns identify less-obvious abstractions
L6
37. UNIT-I 37
How Design Patterns Solve Design Problems
• Determining Object Granularity
– Objects can vary tremendously in size and number
– Facade pattern describes how to represent
subsystems as objects
– Flyweight pattern(Sharing) describes how to
support huge numbers of objects
L6
38. Design Pattern Relationship
• Mapping
Builder
Proxy
saving state
of iteration
Memento
Adapter
Bridge
Command
Iterator
Composite
Decorator
Enumerating
children
adding
respnsibilities
to objects
composed
using
sharing
composites
Flyweight
defining
grammar
Interpreter
Visitor
Chain of
Responsibility
changing skin
versus guts
Strategy
State
sharing
strategies
Mediator Observer
Template Method
defining
algorithm´s
steps
Prototype
Abstract Factory
Singleton Facade
Factory Method
single
instance
single
instance
L6
UNIT-I 38
39. UNIT-I 39
Specifying Object Interfaces
• Interface:
– Set of all signatures defined by an object‘s operations
– Any request matching a signature in the objects interface
may be sent to the object
– Interfaces may contain other interfaces as subsets
• Type:
– Denotes a particular interfaces
– An object may have many types
– Widely different object may share a type
– Objects of the same type need only share parts of their
interfaces
– Asubtype contains the interface of its super type
• Dynamic binding, polymorphism
L6
40. UNIT-I 40
Specifying Object Interfaces
• An object‘s implementation is defined by its class
• The class specifies the object‘s internal data and
defines the operations the object can perform
• Objects is created by instantiating a class
– an object = an instance of a class
• Class inheritance
– parent class and subclass
L6
41. UNIT-I 41
Specifying Object Implementations (cont.)
• Abstract class versus concrete class
– abstract operations
• Override an operation
• Class versus type
– An object‘s class defines how the object is implemented
– An object‘s type only refers to its interface
– An object can have many types, and objects of different
classes can have the same type
L6
42. UNIT-I 42
Specifying Object Implementations (cont.)
• Class versus Interface Inheritance
– class inheritance defines an object‘s implementation in
terms of another object‘s implementation (code and
representation sharing)
– interface inheritance (or subtyping) describes when an
object can be used in place of another
• Many of the design patterns depend on this
distinction
L6
43. UNIT-I 43
Specifying Object Implementations (cont.)
• Programming to an Interface, not an
Implementation
• Benefits
– clients remain unaware of the specific types of
objects they use
– clients remain unaware of the classes that
implement these objects
L6
44. UNIT-I 44
Program to an interface, not an Implementation
• Manipulate objects solely in terms of interfaces
defined by abstract classes!
• Benefits:
1. Clients remain unaware of the specific types of objects they
use.
2. Clients remain unaware of the classes that implement the
objects.
Clients only know about abstract class(es) defining the
interfaces
• Do not declare variables to be instances of particular
concrete classes
• Use creational patterns to create actual objects.
L6
45. UNIT-I 45
Favor object composition over class inheritance
• White-box reuse:
– Reuse by sub classing (class inheritance)
– Internals of parent classes are often visible to subclasses
– works statically, compile-time approach
– Inheritance breaks encapsulation
• Black-box reuse:
– Reuse by object composition
– Requires objects to have well-defined interfaces
– No internal details of objects are visible
L6
46. UNIT-I 46
Putting Reuse Mechanisms to Work
• Inheritance versus Composition
• Delegation
• Inheritance versus Parameterized Types
L6
47. UNIT-I 47
Inheritance versus Composition
• Two most common techniques for reuse
– class inheritance
• white-box reuse
– object composition
• black-box reuse
• Class inheritance
– advantages
• static, straightforward to use
• make the implementations being reuse more easily
L6
48. UNIT-I 48
Inheritance versus Composition (cont.)
• Class inheritance (cont.)
– disadvantages
• the implementations inherited can‘t be changed at
run time
• parent classes often define at least part of their
subclasses‘ physical representation
– breaks encapsulation
• implementation dependencies can cause problems
when you‘re trying to reuse a subclass
L6
49. UNIT-I 49
Inheritance versus Composition (cont.)
• Object composition
– dynamic at run time
– composition requires objects to respect each
others‘ interfaces
• but does not break encapsulation
– any object can be replaced at run time
– Favoring object composition over class
inheritance helps you keep each class
encapsulated and focused on one task
L6
50. UNIT-I 50
Inheritance versus Composition (cont.)
• Object composition (cont.)
– class and class hierarchies will remain small
– but will have more objects
• Favor object composition over class
inheritance
• Inheritance and object composition should
work together
L6
51. Delegation
• Two objects are involved in handling a
request: a receiving object delegates
operations to its delegate
Window
Area()
Rectangle
Area()
width
height
rectangle
UNIT-I 51
L6
52. UNIT-I 52
Delegation (cont.)
• Makes it easy to compose behaviors at run-time and
to change the way they‘re composed
• Disadvantage:dynamic, highly parameterized
software is harder to understand than more static
software
• Delegation is a good design choice only when it
simplifies more than it complicates
• Delegation is an extreme example of object
composition
L6
53. UNIT-I 53
Inheritance versus Parameterized Types
• Let you define a type without specifying all the
other types it uses, the unspecified types are
supplied as parameters at the point of use
• Parameterized types, generics, or templates
• Parameterized types give us a third way to
compose behavior in object-oriented systems
L6
54. UNIT-I 54
Inheritance versus Parameterized Types (cont.)
• Three ways to compose
– object composition lets you change the behavior being
composed at run-time, but it requires indirection and
can be less efficient
– inheritance lets you provide default implementations
for operations and lets subclasses override them
– parameterized types let you change the types that a
class can use
L6
55. UNIT-I 55
Relating Run-Time and Compile-Time Structures
• An object-oriented program‘s run-time structure often
bears little resemblance to its code structure
• The code structure is frozen at compile-time
• Aprogram‘s run-time structure consists of rapidly
changing networks of communicating objects
• aggregation versus acquaintance (association)
– part-of versus knows of
L6
56. UNIT-I 56
Relating Run-Time and Compile-Time Structures
• The distinction between acquaintance and
aggregation is determined more by intent
than by explicit language mechanisms
• The system‘s run-time structure must be
imposed more by the designer than the
language
L6
57. UNIT-I 57
Designing for Change
• Adesign that doesn‘t take change into
account risks major redesign in the future
• Design patterns help you avoid this by
ensuring that a system can change in
specific ways
– each design pattern lets some aspect of system
structure vary independently of other aspects
L6
58. UNIT-I 58
Common Causes of Redesign
• Creating an object by specifying a class
explicitly
• Dependence on specific operations
• Dependence on hardware and software
platform
• Dependence on object representations or
implementations
• Algorithmic dependencies
L6
59. UNIT-I 59
Common Causes of Redesign (cont.)
• Tight coupling
• Extending functionality by subclassing
• Inability to alter classes conveniently
L6
60. UNIT-I 60
Design for Change (cont.)
• Design patterns in application programs
– Design patterns that reduce dependencies can
increase internal reuse
– Design patterns also make an application more
maintainable when they‘re used to limit
platform dependencies and to layer a system
L6
61. UNIT-I 61
Design for Change (cont.)
• Design patterns in toolkits
– Atoolkit is a set of related and reusable classes
designed to provide useful, general-purpose
functionality
– Toolkits emphasize code reuse. They are the
object-oriented equivalent of subroutine
libraries
– Toolkit design is arguably harder than
application design
L6
62. UNIT-I 62
Design for Change (cont.)
• Design patterns in framework
– A framework is a set of cooperating classes that make
up a reusable design for a specific class of software
– You customize a framework to a particular application
by creating application-specific subclasses of abstract
classes from the framework
– The framework dictates the architecture of your
application
L6
63. UNIT-I 63
Design for Change (cont.)
• Design patterns in framework (cont.)
– Frameworks emphasize design reuse over code reuse
– When you use a toolkit, you write the main body of the
application and call the code you want to reuse. When
you use a framework, you reuse the main body and
write the code it calls.
– Advantages: build an application faster, easier to
maintain, and more consistent to their users
L6
64. UNIT-I 64
Design for Change (cont.)
• Design patterns in framework (cont.)
– Mature frameworks usually incorporate several design
patterns
– People who know the patterns gain insight into the
framework faster
– differences between framework and design pattern
• design patterns are more abstract than frameworks
• design patterns are smaller architectural elements than frameworks
• design patterns are less specialized than frameworks
L6
65. UNIT-I 65
How To Select a Design Pattern
Consider how design patterns solve design Problems.
Scan Intent sections.
Study how patterns interrelate.
Study patterns of like purpose.
Examine a Cause of redesign.
Consider what should be variable in your design.
L7
67. How To Use a Design Pattern
Read the pattern once through for an overview.
Go Back and study the Structure, Participants ,and Collaborations
sections.
Look At the Sample Code section to see a concrete
Example of the pattern in code.
Choose names for pattern participants that are meaningful in the
application context.
Define the classes.
Define App’n-specific names for operations in the Pattern
Implement the operations to carry out responsibilities in the
pattern.
UNIT-I 63
L8
72. Design Problems in LEXI-Document Editor
This chapter presents a case study in the design of “What You See Is
What You Get” (WYSIWYG) document editor called Lexi (Lexi’s design is
based on Doc, a text editing application developed by Calder).
A WYSIWYG representation of the document occupies the large
rectangular area in the centre.
The document can mix text and graphics freely in a variety of
formatting styles.
Surrounding the document are the usual pull-down menus and
scrollbars, a collection of page icons for jumping to a particular page in
the document.
73.
74. Design Problems in LEXI
Seven Problems
1. Document Structure
2. Formatting
3. Embellishing(Make more attractive by adding ornament, color,
etc) the user interface
4. Supporting multiple look-and-feel standards
5. Supporting multiple window systems
6. User Operations
7. Spelling checking and hyphenation(to separate the parts of a
compound word)
75. Design Problems in LEXI-Document Editor
• Seven problems in Lexis's design
1. Document Structure
The choice of internal representation for the document affects nearly every aspect of
Lexis's design. All editing , formatting, displaying, and textual analysis will require
traversing the representation.
2. Formatting
How does Lexi actually arrange text and graphics into lines and columns?
What objects are responsible for carrying out different formatting policies?
How do these policies interact with the document‘s internal representation?
3. Embellishing(Make more attractive by adding ornament, color, etc) the user interface
Lexis user interface include scroll bar, borders and drop shadows that embellish the
WYSIWYG document interface. Such embellishments are likely to change as Lexis user
interface evolves.
UNIT-II 68
L1
76. UNIT-I 69
4. Supporting multiple look-and-feel standards
Lexi should adapt easily to different look-and-feel standards such as Motif (a pattern or design)
and Presentation Manager (PM) without major modification.
5. Supporting multiple window systems
Different look-and-feel standards are usually implemented on different window system. Lexi‘s
design should be independent of the window system as possible.
6. User Operations
User control Lexi through various interfaces, including buttons and pull-down menus. The
functionality beyond these interfaces is scattered throughout the objects in the application.
7. Spelling checking and hyphenation
How does Lexi support analytical operations checking for misspelled words and
determining hyphenation points? How can we minimize the number of classes we have to
modify to add a new analytical operation?
78. UNIT-II 78
1. Document Structure
Goals:
– present document‘s visual aspects
– drawing, hit detection, alignment
– support physical structure
(e.g., lines, columns)
Constraints/forces:
– treat text & graphics uniformly
– no distinction between one & many
L1
79. UNIT-II 79
Document Structure
• The internal representation for a document
• The internal representation should support
– maintaining the document‘s physical structure
– generating and presenting the document visually
– mapping positions on the display to elements in the
internal representations
L1
80. UNIT-II 80
Document Structure (cont.)
• Some constraints
– we should treat text and graphics uniformly
– our implementation shouldn‘t have to distinguish between single
elements and groups of elements in the internal representation
• Recursive Composition
– a common way to represent hierarchically structured
information
L1
82. UNIT-II 82
Document Structure (cont.)
• Glyphs(a symbolic figure)
– an abstract class for all objects that can appear in a document
structure
– three basic responsibilities, they know
• how to draw themselves, what space they occupy, and their
children and parent
• Composite Pattern
– captures the essence of recursive composition in object-oriented
terms
L1
85. UNIT-II 85
2. Formatting
• Astructure that corresponds to a properly
formatted document
• Representation and formatting are distinct
– the ability to capture the document‘s physical structure
doesn‘t tell us how to arrive at a particular structure
• here, we‘ll restrict ―formatting‖ to mean breaking
a collection of glyphs in to lines
L2
86. UNIT-II 86
Formatting (cont.)
• Encapsulating the formatting algorithm
– keep formatting algorithms completely
independent of the document structure
– make it is easy to change the formatting
algorithm
– We‘ll define a separate class hierarchy for
objects that encapsulate formatting algorithms
L2
87. UNIT-II 87
Formatting (cont.)
• Compositor and Composition
– We‘ll define a Compositor class for objects that can
encapsulate a formatting algorithm
– The glyphs Compositor formats are the children of a
special Glyph subclass called Composition
– When the composition needs formatting, it calls its
compositor‘s Compose operation
– Each Compositor subclass can implement a different line
breaking algorithm
L2
89. UNIT-II 89
Formatting (cont.)
• Compositor and Composition (cont.)
– The Compositor-Composition class split ensures a
strong separation between code that supports the
document‘s physical structure and the code for different
formatting algorithms
• Strategy pattern
– intent: encapsulating an algorithm in an object
– Compositors are strategies.Acomposition is the
context for a compositor strategy
L2
92. UNIT-II 92
Embellishing the User Interface
• Considering adds a border around the text editing
area and scrollbars that let the user view the different
parts of the page here
• Transparent Enclosure
– inheritance-based approach will result in some problems
• Composition, ScollableComposition,
BorderedScrollableComposition, …
– object composition offers a potentially more workable and
flexible extension mechanism
L3
93. UNIT-II 93
Embellishing the User Interface
(cont.)
• Transparent enclosure (cont.)
– object composition (cont.)
• Border and Scroller should be a subclass of Glyph
– two notions
• single-child (single-component) composition
• compatible interfaces
L3
94. UNIT-II 87
Embellishing the User Interface
(cont.)
• Monoglyph
– We can apply the concept of transparent enclosure to all
glyphs that embellish other glyphs
– the class, Monoglyph
• Decorator Pattern
– captures class and
object relationships
that support
embellishment by
transparent enclosure
void MonoGlyph::Draw(Window* w) {
_component-> Draw(w);
}
void Border:: Draw(Window * w) {
MonoGlyph::Draw(w);
DrawBorder(w);
}
L3
97. 97
Supporting Multiple Look-and-
Feel Standards
• Design to support the look-and-feel changing at run-
time
• Abstracting Object Creation
– widgets
– two sets of widget glyph classes for this purpose
• a set of abstract glyph subclasses for each category of widget glyph
(e.g., ScrollBar)
• a set of concrete subclasses for each abstract subclass that
implement different look-and-feel standards (e.g., MotifScrollBar
and PMScrollBar)
L4
98. 98
Supporting Multiple Look-and-
Feel Standards (cont.)
• Abstracting Object Creation (cont.)
– Lexi needs a way to determine the look-and-
feel standard being targeted
– We must avoid making explicit constructor
calls
– We must also be able to replace an entire
widget set easily
– We can achieve both by abstracting the process
of object creation
L4
99. 99
Supporting Multiple Look-and-
Feel Standards (cont.)
• Factories and Product Classes
– Factories create product objects
– The example
• Abstract Factory Pattern
– capture how to create families of related
product objects without instantiating classes
directly
L4
102. 10
2
Supporting Multiple Window
Systems
• We‘d like Lexi to run on many existing window systems
having different programming interfaces
• Can we use anAbstract Factory?
– As the different programming interfaces on these existing
window systems, theAbstract Factory pattern doesn‘ t work
– We need a uniform set of windowing abstractions that lets us
take different window system impelementations and slide any
one of them under a common interface
L5
103. 10
3
Supporting Multiple Window
Systems (cont.)
• Encapsulating Implementation Dependencies
– The Window class interface encapsulates the things
windows tend to do across window systems
– The Window class is an abstract class
– Where does the implementation live?
• Window and WindowImp
• Bridge Pattern
– to allow separate class hierarchies to work together even as
they evolve independently
L5
107. 107
User Operations
• Requirements
– Lexi provides different user interfaces for the
operations it supported
– These operations are implemented in many different
classes
– Lexi supports undo and redo
• The challenge is to come up with a simple and
extensible mechanism that satisfies all of these
needs
L6
108. 108
User Operations (cont.)
• Encapsulating a Request
– We could parameterize MenuItem with a function to
call, but that‘s not a complete solution
• it doesn‘t address the undo/redo problem
• it‘s hard to associate state with a function
• functions are hard to extent, and it‘s hard to reuse part of them
– We should parameterize MenuItems with an object, not
a function
L6
109. 109
User Operations (cont.)
• Command Class and Subclasses
– The Command abstract class consists of a
single abstract operation called Execute
– MenuItem can store a Command object that
encapsulates a request
– When a user choose a particular menu item, the
MenuItem simply calls Execute on its
Command object to carry out the request
L6
112. 112
User Operations (cont.)
• Undoability
– To undo and redo commands, we add an Unexecute
operation to Command‘s interface
– Aconcrete Command would store the state of the
Command for Unexecute
– Reversible operation returns a Boolean value to
determine if a command is undoable
• Command History
– a list of commands that have been executed
L6
113. Implementing a Command History
• The command history can be seen as a list of past
commands commands
• As new commands are executed they are added to
the front of the history
present
113
past commands
L6
114. • To undo a command, unexecute() is called on the
command on the front of the list
• The ―
present‖ position is moved past the last
command
Undoing the Last Command
unexecute()
present present
114
L6
115. • To undo the previous command, unexecute() is
called on the next command in the history
• The present pointer is moved to point before that
command
present
Undoing the Previous Command
unexecute()
present
115
L6
116. Redoing the Next Command
execute()
• To redo the command that was just undone,
execute() is called on that command
• The present pointer is moved up past that
command
present
present
UNIT-II 116
L6
117. 117
The Command Pattern
• Encapsulate a request as an object
• The Command Patterns lets you
– parameterize clients with different requests
– queue or log requests
– support undoable operations
• Also KnownAs:Action, Transaction
• Covered on pg. 233 in the book
L6
118. 118
Spelling Checking & Hyphenation
Goals:
– analyze text for spelling errors
– introduce potential hyphenation sites
Constraints/forces:
– support multiple algorithms
– don‘t tightly couple algorithms with document
structure
L7
119. Spelling Checking & Hyphenation (cont‘d)
119
Solution: Encapsulate Traversal
Iterator
– encapsulates a
traversal algorithm
without exposing
representation details
to callers
– uses Glyph‘s child
enumeration
operation
– This is an example of
a preorder iterator
L7
120. Spelling Checking & Hyphenation (cont‘d)
object behavioral
ITERA
TOR
Intent
access elements of a container without exposing its representation
Applicability
– require multiple traversal algorithms over a container
– require a uniform traversal interface over different containers
– when container classes & traversal algorithm must vary independently
Structure
L7
120
121. 114
Spelling Checking & Hyphenation (cont‘d)
ITERATOR (cont‘d) object behavioral
cout << endl;
return 0;
Iterators are used heavily in the C++ Standard
Template Library (STL)
int main (int argc, char *argv[])
{
vector<string> args;
for (int i = 0; i < argc; i++)
args.push_back (string (argv[i]));
for (vector<string>::iterator i (args.begin ());i != args.end (); i++)
cout << *i;
The same iterator pattern can be
applied to any STL container!
}
for (Glyph::iterator i = glyphs.begin (); i != glyphs.end ();i++)
...
L7
122. 115
Spelling Checking & Hyphenation (cont‘d)
ITERATOR (cont‘d) object behavioral
Consequences
+ flexibility: aggregate & traversal are independent
-multiple iterators & multiple traversal algorithms
– additional communication overhead between iterator & aggregate
Implementation
– internal versus external iterators
– violating the object structure‘s encapsulation
– robust iterators
– synchronization overhead in multi-threaded programs
– batching in distributed & concurrent programs
Known Uses
– C++ STL iterators
– JDK Enumeration, Iterator
– Unidraw Iterator
L7
123. 123
Spelling Checking & Hyphenation (cont‘d)
Visitor
• defines action(s) at each step of traversal
• avoids wiring action(s) into Glyphs
• iterator calls glyph‘s accept(Visitor) at each node
• accept() calls back on visitor (a form of static
polymorphism based on method overloading by type)
void Character::accept (Visitor &v) { v.visit (*this); }
class Visitor {
public:
virtual void visit (Character &);
virtual void visit (Rectangle &);
virtual void visit (Row &);
// etc. for all relevant Glyph subclasses
};
L7
124. 124
Spelling Checking & Hyphenation (cont‘d)
SpellingCheckerVisitor
• gets character code from each character glyph
Can define getCharCode() operation just on Character()
class
• checks words accumulated from character glyphs
• combine with PreorderIterator
class SpellCheckerVisitor : public Visitor {
public:
virtual void visit (Character &);
virtual void visit (Rectangle &);
virtual void visit (Row &);
// etc. for all relevant Glyph subclasses
Private:
std::string accumulator_;
};
L7
125. Spelling Checking & Hyphenation (cont‘d)
Accumulating Words
Spelling check
performed when a non
alphabetic character it
reached
L7
125
126. Spelling Checking & Hyphenation (cont‘d)
Interaction Diagram
• The iterator controls the order in which accept() is called on each glyph in
the composition
• accept() then visits the glyph to perform the desired action
• The Visitor can be sub-classed to implement various desired actions
126
L7
127. 127
Spelling Checking & Hyphenation (cont‘d)
HyphenationVisitor
• gets character code from each character glyph
• examines words accumulated from character glyphs
• at potential hyphenation point, inserts a...
class HyphenationVisitor : public Visitor {
public:
void visit (Character &);
void visit (Rectangle &);
void visit (Row &);
// etc. for all relevant Glyph subclasses
};
L7
128. Spelling Checking & Hyphenation (cont‘d)
Discretionary(left to individual choice or judgment) Glyph
• looks like a hyphen when at end of a line
• has no appearance otherwise
• Compositor considers its presence when determining
linebreaks
L7
128
129. Spelling Checking & Hyphenation (cont‘d)
VISITOR object behavioral
Intent
centralize operations on an object structure so that they can vary
independently but still behave polymorphically
Applicability
– when classes define many unrelated operations
– class relationships of objects in the structure rarely change, but the
operations on them change often
– algorithms keep state that‘s updated during traversal
Structure
L7
129
130. 130
Spelling Checking & Hyphenation (cont‘d)
VISITOR (cont‘d) object behavioral
SpellCheckerVisitor spell_check_visitor;
for (Glyph::iterator i = glyphs.begin ();
i != glyphs.end ();
i++) {
(*i)->accept (spell_check_visitor);
}
HyphenationVisitor hyphenation_visitor;
for (Glyph::iterator i = glyphs.begin ();
i != glyphs.end ();
i++) {
(*i)->accept (hyphenation_visitor);
}
L7
131. 124
Spelling Checking & Hyphenation (cont‘d)
VISITOR (cont‘d)
Consequences
object behavioral
+ flexibility: visitor & object structure are independent
+ localized functionality
– circular dependency between Visitor & Element interfaces
– Visitor brittle to new ConcreteElement classes
Implementation
– double dispatch
– general interface to elements of object structure
Known Uses
– ProgramNodeEnumerator in Smalltalk-80 compiler
– IRIS Inventor scene rendering
– TAO IDL compiler to handle different backends
L8
132. 132
Part III: Wrap-Up
Concluding Remarks
• design reuse
• uniform design vocabulary
• understanding, restructuring, & team
communication
• provides the basis for automation
• a ―
new‖ way to think about design
L8
133. 133
Pattern References
Books
Timeless Way of Building, Alexander, ISBN 0-19-502402-8
APattern Language, Alexander, 0-19-501-919-9
Design Patterns, Gamma, et al., 0-201-63361-2 CD version 0-201-63498-8
Pattern-Oriented Software Architecture, Vol. 1, Buschmann, et al.,
0-471-95869-7
Pattern-Oriented Software Architecture, Vol. 2, Schmidt, et al.,
0-471-60695-2
Pattern-Oriented Software Architecture, Vol. 3, Jain & Kircher,
0-470-84525-2
Pattern-Oriented Software Architecture, Vol. 4, Buschmann, et al.,
0-470-05902-8
L8
134. 134
Pattern References (cont‘d)
More Books
Analysis Patterns, Fowler; 0-201-89542-0
Concurrent Programming in Java, 2nd ed., Lea, 0-201-31009-0
Pattern Languages of Program Design
Vol. 1, Coplien, et al., eds., ISBN 0-201-60734-4
Vol. 2, Vlissides, et al., eds., 0-201-89527-7
Vol. 3, Martin, et al., eds., 0-201-31011-2
Vol. 4, Harrison, et al., eds., 0-201-43304-4
Vol. 5, Manolescu, et al., eds., 0-321-32194-4
AntiPatterns, Brown, et al., 0-471-19713-0
Applying UML & Patterns, 2nd ed., Larman, 0-13-092569-1
Pattern Hatching, Vlissides, 0-201-43293-5
The Pattern Almanac 2000, Rising, 0-201-61567-3
L8
135. 135
Pattern References (cont‘d)
Even More Books
Small Memory Software, Noble & Weir, 0-201-59607-5
Microsoft Visual Basic Design Patterns, Stamatakis, 1-572-31957-7
Smalltalk Best Practice Patterns, Beck; 0-13-476904-X
The Design Patterns Smalltalk Companion, Alpert, et al.,
0-201-18462-1
Modern C++ Design, Alexandrescu, ISBN 0-201-70431-5
Building Parsers with Java, Metsker, 0-201-71962-2
Core J2EE Patterns,Alur, et al., 0-130-64884-1
Design Patterns Explained, Shalloway & Trott, 0-201-71594-5
The Joy of Patterns, Goldfedder, 0-201-65759-7
The Manager Pool, Olson & Stimmel, 0-201-72583-5
L8
136. 136
Pattern References (cont‘d)
Early Papers
―Object-Oriented Patterns,‖ P. Coad; Comm. of theACM, 9/92
―Documenting Frameworks using Patterns,‖ R. Johnson; OOPSLA ‘92
―Design Patterns: Abstraction & Reuse of Object-Oriented Design,‖
Gamma, Helm, Johnson, Vlissides, ECOOP ‘93
Articles
Java Report, Java Pro, JOOP, Dr. Dobb‘s Journal,
Java Developers Journal, C++ Report
L8
137. 137
Pattern-Oriented Conferences
PLoP2007: Pattern Languages of Programs
October 2007, Collocated with OOPSLA
EuroPLoP2007, July 2007, Kloster Irsee, Germany
…
See hillside.net/conferences/ for
up-to-the-minute info.
L8
138. 138
Mailing Lists
patterns@cs.uiuc.edu: present & refine patterns
patterns-discussion@cs.uiuc.edu: general discussion
gang-of-4-patterns@cs.uiuc.edu: discussion on Design Patterns
siemens-patterns@cs.uiuc.edu: discussion on
Pattern-Oriented Software Architecture
ui-patterns@cs.uiuc.edu: discussion on user interface patterns
business-patterns@cs.uiuc.edu: discussion on patterns for business processes
ipc-patterns@cs.uiuc.edu: discussion on patterns for distributed systems
See http://hillside.net/patterns/mailing.htm for an up-to-date list.
L8
140. 140
What are creational patterns?
• The Creational Designpatternsthatdealwithobjectcreation
mechanisms,tryingto createobjectsinamannersuitableto thesituation.
• The creational patterns aim to separate a system from how its
objects are created, composed, and represented.
• They increase the system’s flexibility in terms of the what, who,
how, and when of object creation.
• Creational design patterns are composed of two dominant
ideas.
1. Encapsulating (to express or show the most important facts)
knowledge about which concrete classes the system uses.
2. Hiding how instances of these concrete classes are created and
combined.
L1
141. 141
Benefits of creational patterns
• Creational patterns let you program to an interface defined
by an abstract class
• That lets you configure a system with “product”
objects that vary widely in structure and functionality
• Example: GUI systems
– InterViews GUI class library
– Multiple look-and-feels
– Abstract Factories for different screen
components
L1
142. 142
Benefits of creational patterns
• Generic instantiation – Objects are instantiated without
havingto identifyaspecificclass typein clientcode(Abstract
Factory
,Factory)
• Simplicity – Make instantiation easier: callers do not have to
write long complex code to instantiate and set up an object
(Builder,Prototype pattern)
• Creationconstraints – Creationalpatterns canput bounds on
whocancreateobjects,howtheyare created,and whentheyare
created
L1
145. 145
Abstract Factory
Provide an interface for creating families of related
or dependent objects without specifying their
concrete classes
L2
146. 146
ABSTRACT FACTORY
(Object Creational)
• Intent:
– Provide an interface for creating families of
related or dependent objects without specifying
their concrete classes
• Also KnownAs: Kit.
L2
147. 147
Motivation
• Motivation:
•User interface toolkit supports multiple look- and-
feel standards
(Motif (a decorative image or design, especially a
repeated one forming a pattern.), Presentation
Manager)
•Different appearances and behaviors for UI
widgets(an application, or a component of an
interface, that enables a user to perform a
function or access a service)
•Apps should not hard-code its widgets
L2
149. 149
• Solution:
•Abstract Widget Factory class
•Interfaces for creating each basic kind of
widget
•Abstract class for each kind of widgets,
•Concrete classes implement specific look-
and-feel.
Solution:
L2
150. 150
Applicability
Use theAbstract Factory pattern when
– Asystem should be independent of how its products
are created, composed, and represented
– A system should be configured with one of multiple
families of produces
– A family of related product objects is designed to be
used together, and you need to enforce this constraint
– You want to provide a class library of products, and
you want to reveal just their interfaces, not their
implementations
L2
152. 152
ABSTRACT FACTORY
Participants
• AbtractFactory
– Declares interface for operations that create
abstract product objects
• ConcreteFactory
– Implements operations to create concrete product
objects
• AbstractProduct
– Declares an interface for a type of product object
L2
153. 153
• ABSTRACT FACTORY
Participants(cont..)
• Concrete Product:
•Defines a product object to be created by concrete
factory
•Implements the abstract product interface
• Client:
•Uses only interfaces declared byAbstract Factory
andAbstractProduct classes
L2
154. 154
Collaborators
• Usually only one ConcreteFactory instance is used fo
an activation, matched to a specific application
context. It builds a specific product family for client
use the client doesn‘t care which family is used i
simply needs the services appropriate for the current
context.
• The client may use theAbstractFactory interface to
initiate creation, or some other agent may use the
AbstractFactory on the client‘s behalf.
L2
155. 155
Presentation Remark
• Here, we often use a sequence diagram
(event-trace) to show the dynamic
interactions between participants.
• For the Abstract Factory Pattern, the
dynamic interaction is simple, and a
sequence diagram would not add much new
information.
L2
156. 150
Consequences
• TheAbstract Factory Pattern has the following
benefits:
– It isolates concrete classes from the client.
• You use the Abstract Factory to control the classes of objects the
client creates.
• Product names are isolated in the implementation of the
ConcreteFactory, clients use the instances through their abstract
interfaces.
– Exchanging product families is easy.
• None of the client code breaks because the abstract interfaces
don‘t change.
• Because the abstract factory creates a complete family of
products, the whole product family changes when the concrete
factory is changed.
L2
157. 151
Consequences
• More benefits of theAbstract Factory
Pattern
– It supports the imposition of constraints on
product families, e.g., always useA1 and B1
together, otherwise useA2 and B2 together.
L2
158. – Adding new kinds of products to existing
factory is difficult.
• Adding a new product requires extending the
abstract interface which implies that all of its
derived concrete classes also must change.
• Essentially everything must change to support and
use the new product family
– abstract factory interface is extended
– derived concrete factories must implement the extensions 152
Consequences
• TheAbstract Factory pattern has the
following liability:
L2
159. – alternately concrete factory can be implemented using
prototype.
• only one is needed for all families of products
• product classes now have special requirements - they
participate in the creation
159
Implementation
• Concrete factories are often implemented as
singletons.
• Creating the products
– Concrete factory usually use the factory method.
• simple
• new concrete factory is required for each product family
L2
160. 155
Implementation
• Defining extensible factories by using
create function with an argument
– only one virtual create function is needed for
theAbstractFactory interface
– all products created by a factory must have the
same base class or be able to be safely coerced
to a given type
– it is difficult to implement subclass specific
operations
L2
161. 161
Code Examples
• Skeleton Example
– Abstract Factory Structure
– Skeleton Code
• Neural Net Example
– Neural Net Physical Structure
– Neural Net Logical Structure
– Simulated Neural Net Example
L2
162. If we want to create a Mac style scroll bar, we can write a
code like this:
ScrollBar *sb = new MacScrollBar;
But if we're going to make it work across any platform, we
should write a code something similar to this:
ScrollBar *sb = guiFactory->createScrollBar();
The instance variable guiFactory is initialized as:
GUIFactory *guiFactory = new MacFactory;
163. Here is the example code:
#include <iostream>
class Button
{
public: virtual void paint() = 0;
};
class WinButton : public Button
{
public: void paint ()
{
std::cout << " Window Button n";
}
};
class MacButton : public Button
{
public: void paint ()
{
164. std::cout << " Mac Button n";
}
};
class ScrollBar
{
public: virtual void paint() = 0;
};
class WinScrollBar : public ScrollBar
{
public: void paint ()
{
std::cout << " Window ScrollBar n";
}
};
class MacScrollBar : public ScrollBar
{
public: void paint()
{
std::cout << " Mac ScrollBar n";
}
};
class GUIFactory
{
public: virtual Button* createButton () = 0;
virtual ScrollBar* createScrollBar () = 0;
};
class WinFactory : public GUIFactory
{
public: Button* createButton ()
{
return new WinButton;
}
ScrollBar* createScrollBar (){
return new WinScrollBar;
}
};
class MacFactory : public GUIFactory { public:
Button* createButton ()
{
return new MacButton; } ScrollBar*
createScrollBar ()
{
return new MacScrollBar;
}
};
166. 156
Know Uses
• Interviews
– used to generate look and feel for specific user
interface objects
– uses the Kit suffix to denote AbstractFactory classes,
e.g., WidgetKit and DialogKit.
• also includes a layoutKit that generates different
composite objects depending on the needs of the
current context
ET++(A Smalltalk-like system for Suns, built on C++)
– another windowing library that uses the
AbstractFactory to achieve portability across different
window systems (X Windows and SunView).
• COM – Microsoft‘s Component Object Model
L2
167. 167
Related Patterns
• Factory Method - a virtual constructor
• Prototype -asks products to clone
themselves
• Singleton -allows creation of only a single
instance
L2
168. 168
BUILDER
(Object Creational)
• Intent:
Separate the construction of a complex object from
its representation so that the same construction
process can create different representations
• Motivation:
– RTF(Rich Text Format) reader should be able to
convert RTF to many text format
– Adding new conversions without modifying the
reader should be easy
L3
169.
170. 170
• Solution:
•Configure RTFReader class with a Text
Converter object
•Subclasses of Text Converter specialize in
different conversions and formats
•TextWidgetConverter will produce a
complex UI object and lets the user see and
edit the text
L3
171. 171
Why do we use Builder?
• Common manner
to Create an
Instance
– Constructor!
– Each Parts
determined by
Parameter of the
Constructor
public class Room {
private int area;
private int windows;
public String purpose;
Room() {
}
Room(int newArea, int newWindows,
String newPurpose){
area = newArea;
windows = newWindows;
purpose = newPurpose;
}
}
There are Only 2 different ways
to Create an Instance part-by-part.
L3
172. 172
Why do we use Builder?
• In the previous example,
– We can either determine all the arguments
or determine nothing and just construct.
We can‘t determine arguments partially.
– We can‘t control whole process to
Create an instance.
– Restriction of ways to Create an Object
☞ Bad Abstraction & Flexibility
L3
174. Applicability
Use the Builder pattern when
The algorithm for creating a complex object should be
independent of the parts that make up the object and how
they are assembled
The construction process must allow different
representations for the object that is constructed.
176. Participants
Builder (TextConverter)
Specifies an abstract interface for creating parts of a Product object.
ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter)
Constructs and assembles parts of the product by implementing the Builder interface.
Defines and keeps track of the representation it creates.
Provides an interface for retrieving the product (e.g., GetASCIIText, GetTextWidget).
Director (RTFReader)
Constructs an object using the Builder interface.
Product (ASCIIText, TeXText, TextWidget)
Represents the complex object under construction. ConcreteBuilder builds the
product's internal representation and defines the process by which it's assembled.
Includes classes that define the constituent parts, including interfaces for assembling the
parts into the final result.
177. Collaborations
The client creates the Director object and configures it
with the desired Builder object.
Director notifies the builder whenever a part of the
product should be built.
Builder handles requests from the director and adds
parts to the product.
The client retrieves the product from the builder.
The following interaction diagram illustrates how
Builder and Director cooperate with a client.
178.
179. Consequences
1. It lets you vary a product's internal representation.
2. It isolates code for construction and representation.
3. It gives you finer control over the construction process.
180. Implementation
Typically there's an abstract Builder class that defines an operation
for each component that a director may ask it to create. The
operations do nothing by default. A ConcreteBuilder class
overrides operations for components it's interested in creating.
Here are other implementation issues to consider:
1. Assembly and construction interface.
2. Why no abstract class for products?
3. Empty methods as default in Builder.
184. Known Uses
The RTF converter application is from ET++ [WGM88].
Its text building block uses a builder to process text stored in the RTF format.
Builder is a common pattern in Smalltalk-80 [Par90]:
The Parser class in the compiler subsystem is a Director that takes a
ProgramNodeBuilder object as an argument. A Parser object notifies its
ProgramNodeBuilder object each time it recognizes a syntactic construct. When the
parser is done, it asks the builder for the parse tree it built and returns it to the
client.
ClassBuilder is a builder that Classes use to create subclasses for themselves. In
this case a Class is both the Director and the Product.
ByteCodeStream is a builder that creates a compiled method as a byte array.
ByteCodeStream is a nonstandard use of the Builder pattern, because the complex
object it builds is encoded as a byte array, not as a normal Smalltalk object. But the
interface to ByteCodeStream is typical of a builder, and it would be easy to replace
ByteCodeStream with a different class that represented programs as a composite
object.
185. Related Patterns
Abstract Factory (99) is similar to Builder in that it too
may construct complex objects.
A Composite (183) is what the builder often builds.
186. 186
FACTORY METHOD
(Class Creational)
• 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.
• Motivation:
– Framework use abstract classes to define and maintain
relationships between objects
– Framework has to create objects as well - must instantiate
classes but only knows about abstract classes - which it
cannot instantiate
L4
187. 187
Motivation:
• Motivation: Factory method encapsulates
knowledge of which subclass to create -
moves this knowledge out of the framework
• Also Known As: Virtual Constructor
L4
189. 189
Applicability
• Use the Factory Method pattern when
– a class can´t anticipate the class of objects it must
create.
– a class wants its subclasses to specify the objects
it creates.
– classes delegate responsibility to one of several
helper subclasses, and you want to localize the
knowledge of which helper subclass is the
delegate.
L4
191. Participants
• Product
– Defines the interface of objects the factory method
creates
• ConcreteProduct
– Implements the product interface
• Creator
– Declares the factory method which returns object of type
product
– May contain a default implementation of the factory
method
– Creator relies on its subclasses to define the factory
method so that it returns an instance of the appropriate
Concrete Product.
L4
192. 177
Factory Method
Creator
Product createProduct()
Product
• Defer object instantiation to subclasses
• Eliminates binding of application-specific subclasses
• Connects parallel class hierarchies
• Arelated pattern isAbstractFactory
operation()
ConcreteCreator
Product createProduct()
ConcreteProduct
operation()
return new ConcreteProduct();
L4
194. Collaborations
Creator relies on its subclasses to define the factory
method so that it returns an instance of the appropriate
ConcreteProduct.
Consequences
Factory methods eliminate the need to bind application-specific
classes into your code. The code only deals with the Product
interface; therefore it can work with any user-defined
ConcreteProduct classes.
A potential disadvantage of factory methods is that clients might
have to subclass the Creator class just to create a particular
ConcreteProduct object. Subclassing is fine when the client has to
subclass the Creator class anyway, but otherwise the client now
must deal with another point of evolution.
195. Consequences
Here are two additional consequences of the Factory
Method pattern:
1. Provides hooks for subclasses.
2. Connects parallel class hierarchies.
196. Implementation
Consider the following issues when applying the Factory
Method pattern:
1. Two major varieties.
2. Parameterized factory methods.
3. Language-specific variants and issues.
4. Using templates to avoid subclassing.
5. Naming conventions.
197. Sample Code
The function CreateMaze builds and returns a maze. One
problem with this function is that it hard-codes the classes
of maze, rooms, doors, and walls. We'll introduce factory
methods to let subclasses choose these components. First
we'll define factory methods in MazeGame for creating
the maze, room, wall, and door objects:
class MazeGame
{
public: Maze* CreateMaze(); // factory methods:
virtual Maze* MakeMaze() const
{
return new Maze;
}
virtual Room* MakeRoom(int n) const
{ return new Room(n);
} virtual Wall* MakeWall() const
{
return new Wall;
}
virtual Door* MakeDoor(Room* r1, Room* r2)const
{
return new Door(r1, r2);
}
};
198. Now we can rewrite CreateMaze to use these factory methods: Maze*
MazeGame::CreateMaze ()
{
Maze* aMaze = MakeMaze();
Room* r1 = MakeRoom(1);
Room* r2 = MakeRoom(2);
Door* theDoor = MakeDoor(r1, r2);
aMaze->AddRoom(r1);
aMaze->AddRoom(r2);
r1->SetSide(North, MakeWall());
r1->SetSide(East, theDoor);
r1->SetSide(South, MakeWall());
r1->SetSide(West, MakeWall());
r2->SetSide(North, MakeWall());
r2->SetSide(East, MakeWall());
r2->SetSide(South, MakeWall());
r2->SetSide(West, theDoor); return aMaze;
}
class BombedMazeGame :
public MazeGame
{
public: BombedMazeGame();
virtual Wall* MakeWall() const
{
return new BombedWall;
}
virtual Room* MakeRoom(int n) const
{
return new RoomWithABomb(n); } };
An EnchantedMazeGame variant might be
defined like this: class EnchantedMazeGame :
public MazeGame
{
public: EnchantedMazeGame();
virtual Room* MakeRoom(int n) const
{
return new EnchantedRoom(n, CastSpell());
}
virtual Door* MakeDoor(Room* r1, Room* r2)
const
{
return new DoorNeedingSpell(r1, r2);
}
protected: Spell* CastSpell() const;
};
199. Known Uses
Factory methods pervade toolkits and frameworks. The preceding
document example is a typical use in MacApp and ET++
[WGM88]. The manipulator example is from Unidraw.
Class View in the Smalltalk-80 Model/View/Controller framework
has a method defaultController that creates a controller, and this
might appear to be a factory method [Par90].
But subclasses of View specify the class of their default controller
by defining defaultControllerClass, which returns the class from
which defaultController creates instances. So
defaultControllerClass is the real factory method, that is, the
method that subclasses should override.
200. A more esoteric example in Smalltalk-80 is the factory method
parserClass defined by Behavior (a superclass of all objects
representing classes). This enables a class to use a customized
parser for its source code.
For example, a client can define a class SQLParser to analyze
the source code of a class with embedded SQL statements.
The Behavior class implements parserClass to return the
standard Smalltalk Parser class. A class that includes embedded
SQL statements overrides this method (as a class method) and
returns the SQLParser class.
The Orbix ORB system from IONA Technologies [ION94] uses
Factory Method to generate an appropriate type of proxy (see
Proxy (233)) when an object requests a reference to a remote
object.
Factory Method makes it easy to replace the default proxy with
one that uses client-side caching, for example.
201. Related Patterns
Abstract Factory (99) is often implemented with factory
methods. The Motivation example in the Abstract Factory pattern
illustrates Factory Method as well.
Factory methods are usually called within Template Methods
(360). In the document example above, NewDocument is a
template method.
Prototypes (133) don't require subclassing Creator. However,
they often require an Initialize operation on the Product class.
Creator uses Initialize to initialize the object. Factory Method
doesn't require such an operation.
202. 202
PROTOTYPE
(Object Creational)
• Intent:
– Specify the kinds of objects to create using a
prototypical instance, and create new objects by
copying this prototype.
• Motivation:
– Framework implements Graphic class for
graphical components and GraphicTool class for
tools manipulating/creating those components
L5
203. 203
Motivation
– Actual graphical components are application-
specific
– How to parameterize instances of Graphic Tool
class with type of objects to create?
– Solution: create new objects in Graphic Tool by
cloning a prototype object instance
L5
204. Tool
Manipulate()
Rotate Tool Graphic Tool
Manipulate() Manipulate()
Staff MusicalNote
WholeNote
Return copy of self
HalfNote
Graphic
Draw(Position)
Clone()
p = prototype ->Clone()
while(user drags mouse){
p ->Draw(new position)
}
Insert p into drawing
Draw(Position)
Clone()
Draw(Position)
Clone()
Return copy of self
Draw(Position)
Clone()
prototype
PROTOTYPE
Motivation
204
L5
205. 205
Applicability
• Use the Prototype pattern when a system should
be independent of how its products are created,
composed, and represented;
– when the classes to instantiate are specified at run-
time, for example, by dynamic loading; or
– to avoid building a class hierarchy of factories that
parallels the class hierarchy of products; or
L5
206. 206
Applicability
– when instances of a class can have one of only a
few different combinations of state. It may be
more convenient to install a corresponding
number of prototypes and clone them rather than
instantiating the class manually, each time with
the appropriate state.
L5
207. client
Operation()
p = prototype ->Clone()
ConcretePrototype1
return copy of self
prototype
Prototype
Clone()
return copy of self
Clone()
ConcretePrototype2
Clone()
PROTOTYPE
Structure
207
L5
208. 208
Participants:
• Prototype (Graphic)
– Declares an interface for cloning itself
• ConcretePrototype (Staff, WholeNote, HalfNote)
– Implements an interface for cloning itself
• Client (GraphicTool)
– Creates a new object by asking a prototype to clone itself
Collaborations:
• Aclient asks a prototype to clone Itself.
L5
209. Consequences
Prototype has many of the same consequences that Abstract
Factory (99) and Builder (110) have: It hides the concrete
product classes from the client, thereby reducing the number of
names clients know about. Moreover, these patterns let a client
work with application-specific classes without modification.
Additional benefits of the Prototype pattern are listed below.
1. Adding and removing products at run-time.
2. Specifying new objects by varying values.
3. Specifying new objects by varying structure.
4. Reduced subclassing.
5. Configuring an application with classes dynamically.
210. Implementation Sample Code
Consider the following issues when implementing
prototypes:
1. Using a prototype manager.
2. Implementing the Clone operation.
3. Initializing clones.
Sample Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
const int N = 4;
// Prototype
class Document
{
public:
virtual Document* clone() const = 0;
virtual void store() const = 0;
virtual ~Document() { }
};
// Concrete prototypes : xmlDoc, plainDoc,
spreadsheetDoc
211. class xmlDoc : public Document
{
public:
Document* clone() const { return new xmlDoc; }
void store() const { cout << "xmlDocn"; }
};
class plainDoc : public Document
{
public:
Document* clone() const { return new plainDoc; }
void store() const { cout << "plainDocn"; }
};
class spreadsheetDoc : public Document
{
public:
Document* clone() const { return new spreadsheetDoc; }
void store() const { cout << "spreadsheetDocn"; }
};
// makeDocument() calls Concrete Portotype's clone() method
// inherited from Prototype
class DocumentManager {
public:
static Document* makeDocument( int choice );
~DocumentManager(){}
private:
static Document* mDocTypes[N];
};
Document* DocumentManager::mDocTypes[] =
{
0, new xmlDoc, new plainDoc, new spreadsheetDoc
};
Document* DocumentManager::makeDocument( int choice
)
{
return mDocTypes[choice]->clone();
}
// for_each op ()
struct Destruct
{
void operator()(Document *a) const {
delete a;
}
};
// Client
int main() {
vector<Document*> docs(N);
int choice;
cout << "quit(0), xml(1), plain(2), spreadsheet(3): n";
while (true) {
cout << "Type in your choice (0-3)n";
212. cin >> choice;
if (choice <= 0 || choice >= N)
break;
docs[choice] =
DocumentManager::makeDocument( choice );
}
for (int i = 1; i < docs.size(); ++i)
if(docs[i]) docs[i]->store();
Destruct d;
// this calls Destruct::operator()
for_each(docs.begin(), docs.end(), d);
return 0;
}
Output:
quit(0), xml(1), plain(2), spreadsheet(3):
Type in your choice (0-3)
1
Type in your choice (0-3)
2
Type in your choice (0-3)
3
Type in your choice (0-3)
0
xmlDoc
plainDoc
spreadsheetDoc
213. Known Uses
Perhaps the first example of the Prototype pattern was in
Ivan Sutherland's Sketchpad system [Sut63]. The first
widely known application of the pattern in an object-
oriented language was in ThingLab, where users could
form a compositeobject and then promote it to a prototype
by installing it in a library of reusable objects [Bor81].
Goldberg and Robson mention prototypes as a pattern
[GR83], but Coplien [Cop92] gives a much more complete
description. He describes idioms related to the Prototype
pattern for C++ and gives many examples and variations.
214. Etgdb is a debugger front-end based on ET++ that provides a point-and-click
interface to different line-oriented debuggers. Each debugger has a corresponding
DebuggerAdaptor subclass. For example, GdbAdaptor adapts etgdb to the
command syntax of GNU gdb, while SunDbxAdaptor adapts etgdb to Sun's dbx
debugger. Etgdb does not have a set of DebuggerAdaptor classes hard-coded into
it.
Instead, it reads the name of the adaptor to use from an environment variable,
looks for a prototype with the specified name in a global table, and then clones the
prototype. New debuggers can be added to etgdb by linking it with the
DebuggerAdaptor that works for that debugger.
The "interaction technique library" in Mode Composer stores prototypes of
objects that support various interaction techniques [Sha90]. Any interaction
technique created by the Mode Composer can be used as a prototype by placing it
in this library. The Prototype pattern lets Mode Composer support an unlimited
set of interaction techniques. The music editor example discussed earlier is based
on the Unidraw drawing framework [VL90].
215. Related Patterns
Prototype and Abstract Factory (99) are competing patterns in
some ways, as we discuss at the end of this chapter. They can also
be used together, however. An Abstract Factory might store a set
of prototypes from which to clone and return product objects.
Designs that make heavy use of the Composite (183) and
Decorator (196) patterns often can benefit from Prototype as well.
216. 216
SINGELTON
• Intent:
– Ensure a class only has one instance, and provide
a global point of access to it.
• Motivation:
– Some classes should have exactly one instance
(one print spooler, one file system, one window
manager)
– Aglobal variable makes an object accessible but
doesn‘t prohibit instantiation of multiple objects
– Class should be responsible for keeping track of
its sole interface
L6
217. 217
Applicability
• Use the Singleton pattern when
– there must be exactly one instance of a class, and
it must be accessible to clients from a well-known
access point.
– when the sole instance should be extensible by
subclassing, and clients should be able to use an
extended instance without modifying their code.
L6
219. 219
Participants and Collaborations
• Singleton: Defines an instance operation that lets
clients access its unique interface
• Instance is a class operation (static in Java)
• May be responsible for creating its own unique
instance
• Collaborations: Clients access a Singleton instance
solely through Singleton‘s Instance operation.
L6
220. Consequences
The Singleton pattern has several benefits:
1. Controlled access to sole instance.
2. Reduced name space.
3. Permits refinement of operations and representation.
4. Permits a variable number of instances.
5. More flexible than class operations.
221. 221
Implementation Points
• Generally, a single instance is held by the
object, and controlled by a single interface.
• Sub classing the Singleton may provide
both default and overridden functionality.
L6
222. 222
Singleton – Example 1
• AnApplication class, where instantiating it makes
a connection to the base operating system and sets
up the rest of the toolkit‘s framework for the user
interface.
• In the Qt toolkit:
QApplication* app = new QApplication(argc, argv)
L6
223. 223
Singleton – Example 2
• Astatus bar is required for the application, and
various application pieces need to be able to
update the text to display information to the user.
However, there is only one status bar, and the
interface to it should be limited. It could be
implemented as a Singleton object, allowing only
one instance and a focal point for updates. This
would allow updates to be queued, and prevent
messages from being overwritten too quickly for
the user to read them.
L6
224. Sample Code
#include <iostream>
using namespace std;
class Singleton
{
public: static Singleton *getInstance();
private: Singleton()
{}
static Singleton* instance;
};
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(!instance)
{
instance = new Singleton();
cout << "getInstance():
First instancen";
return instance;
}
else
{
cout << "getInstance():
previous instancen";
return instance;
}
}
int main()
{
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
return 0;
}
Output from the run:
getInstance(): First instance
getInstance(): previous instance
225. Known Uses
An example of the Singleton pattern in Smalltalk-80
[Par90] is the set of changes to the code, which is
ChangeSet current. A more subtle example is the
relationship between classes and their metaclasses. A
metaclass is the class of a class, and each metaclass has
one instance. Metaclasses do not have names (except
indirectly through their sole instance), but they keep track
of their sole instance and will not normally create another.
226. The InterViews user interface toolkit [LCI+92] uses the
Singleton pattern to access the unique instance of its
Session and WidgetKit classes, among others.
Session defines the application's main event dispatch
loop, stores the user's database of stylistic preferences, and
manages connections to one or more physical displays.
WidgetKit is an Abstract Factory (99) for defining the
look and feel of user interface widgets.
The WidgetKit::instance() operation determines the
particular WidgetKit subclass that's instantiated based on
an environment variable that Session defines.
A similar operation on Session determines whether
monochrome or color displays are supported and
configures the singleton Session instance accordingly.
227. Related Patterns
Many patterns can be implemented using the Singleton
pattern.
Abstract Factory (99),
Builder (110), and
Prototype (133).
228. Singleton Code [1]
class Singleton {
public:
static Singleton* Instance();
}
protected:
Singleton();
private:
Static Singleton* _instance
// Only one instance can ever be created.
// Creation hidden inside Instance().
// Cannot access directly.
L6
228
229. 229
Singleton Code [2]
Singleton* Singleton::_instance=0;
Singleton* Singleton:: Instance(){
if (_instance ==0) {
_instance=new Singleton;
}
Return _instance;
} // Clients access the singleton
// exclusively via the Instance member
// function.
L6
232. Structural patterns
Structural patterns are concerned with how classes
and objects are composed to form larger structures.
Structural class patterns use inheritance to compose
interfaces or implementations.
As a simple example,
consider how multiple inheritance mixes two or
more classes into one. The result is a class that
combines the properties of its parent classes. This
pattern is particularly useful for making independently
developed class libraries work together.
Another example is the class form of the Adapter (157)
pattern.
234. 1. Adapter
• Intent:
Convert the interface of a
class into another interface
which is expected by the
client.
• Also KnowAs:
Wrapper
L1
234
235. Sometimes a toolkit class that's designed for reuse isn't reusable
only because its interface doesn't match the domain-specific
interface an application requires. Consider for example a drawing
editor that lets users draw and arrange graphical elements (lines,
polygons, text, etc.) into pictures and diagrams.
The drawing editor's key abstraction is the graphical object,
which has an editable shape and can draw itself. The interface for
graphical objects is defined by an abstract class called Shape.
The editor defines a subclass of Shape for each kind of graphical
object: a LineShape class for lines, a PolygonShape class for
polygons, and so forth.
Classes for elementary geometric shapes like LineShape and
PolygonShape are rather easy to implement, because their
drawing and editing capabilities are inherently limited.
Motivation
236. We can do this in one of two ways:
(1) by inheriting Shape's interface and TextView's
implementation or
(2) by composing a TextView instance within a TextShape
and implementing TextShape in terms of TextView's
interface.
These two approaches correspond to the class and object
versions of the Adapter pattern. We call TextShape an
adapter.
238. Applicability
• Use an existing class whose interface does not
match the requirement
• Create a reusable class though the
interfaces are not necessary compatible
with callers
• Want to use several existing subclasses,but
it is impractical to subclass everyone.
(Object Adapter Only)
238
L1
241. Class Adapter Pattern
• Pros
– Only 1 new object, no additional indirection
– Less code required than the objectAdapter
– Can overrideAdaptee's behaviour as required
• Cons
– Requires sub-classing (tough for single
inheritance)
– Less flexible than objectAdapter
L1
241
242. Object Adapter Pattern
• Pros
– More flexible than classAdapter
– Doesn't require sub-classing to work
– Adapter works withAdaptee and all of its
subclasses
• Cons
– Harder to overrideAdaptee behavior
– Requires more code to implement properly
L1
242
243. Participants
· Target (Shape)
Defines the domain-specific interface that Client uses.
· Client (DrawingEditor)
Collaborates with objects conforming to the Target interface.
· Adaptee (TextView)
Defines an existing interface that needs adapting.
· Adapter (TextShape)
Adapts the interface of Adaptee to the Target interface.
245. Consequences
Class and object adapters have different trade-offs.
A class adapter
adapts Adaptee to Target by committing to a concrete
Adapter class. As a consequence, a class adapter won't
work when we want to adapt a class and all its subclasses.
lets Adapter override some of Adaptee's behavior, since
Adapter is a subclass of Adaptee.
introduces only one object, and no additional pointer
indirection is needed to get to the adaptee.
246. An object adapter
lets a single Adapter work with many Adaptees—that is, the
Adaptee itself and all of its subclasses (if any). The Adapter can also
add functionality to all Adaptees at once.
makes it harder to override Adaptee behavior. It will require
subclassing Adaptee and making Adapter refer to the subclass rather
than the Adaptee itself.
Here are other issues to consider when using the Adapter pattern:
1. How much adapting does Adapter do?
2. Pluggable adapters.
3. Using two-way adapters to provide transparency.
247. Implementation
Although the implementation of Adapter is usually
straightforward, here are some issues to keep in mind:
1. Implementing class adapters in C++.
2. Pluggable adapters.
The narrow interface leads to three implementation
approaches:
a. Using abstract operations.
b. Using delegate objects.
c. Parameterized adapters.
248. 248
Sample Code
• You have
– legacy code
– current client
• Adapter changes interface of legacy code so client
can use it
• Adapter fills the gap b/w two interfaces
• No changes needed for either
– legacy code, or
– client
L1
251. Known Uses
The Motivation example comes from ET++Draw, a drawing
application based on ET++ [WGM88]. ET++Draw reuses the
ET++ classes for text editing by using a TextShape adapter class.
InterViews 2.6 defines an Interactor abstract class for user
interface elements such as scroll bars, buttons, and menus
[VL88]. It also defines a Graphic abstract class for structured
graphic objects such as lines, circles, polygons, and splines.
Both Interactors and Graphics have graphical appearances, but
they have different interfaces and implementations (they share
no common parent class) and are therefore incompatible—you
can't embed a structured graphic object in, say, a dialog box
directly
252. 252
Related Patterns
• Adapter can be similar to the remote form
of Proxy. However, Proxy doesn't change
interfaces.
• Decorator enhances another object
without changing its interface.
• Bridge similar structure to Adapter, but
different intent. Separates interface from
implementation.
L1
254. 254
BRIDGE (Object Structural)
• Intent:
Decouple as abstraction from its implementation
so that the two can vary independently.
• Also KnownAs:
Handle/Body
L2
255. When an abstraction can have one of several possible
implementations, the usual way to accommodate them is to use
inheritance.
An abstract class defines the interface to the abstraction, and
concrete subclasses implement it in different ways. But this
approach isn't always flexible enough.
Inheritance binds an implementation to the abstraction
permanently, which makes it difficult to modify, extend, and
reuse abstractions and implementations independently.
Motivation
256. Consider the implementation of a portable Window abstraction
in a user interface toolkit.
This abstraction should enable us to write applications that
work on both the X Window System and IBM's Presentation
Manager (PM), for example.
Using inheritance, we could define an abstract class Window
and subclasses XWindow and PMWindow that implement the
Window interface for the different platforms
259. 259
Applicability
When you want to avoid a permanent binding between an abstraction and its
implementation.
Both the abstractions and their implementations should be extensible by sub
classing.
Changes in the implementation of an abstraction should have no impact on
clients
When the implementation should be completely hidden from the client. (C++)
When you have a proliferation(the fact of something increasing a lot and
suddenly in number or amount) of classes.
When, unknown to the client, implementations are shared among multiple
objects.
L2
261. Participants
Abstraction (Window)
Defines the abstraction's interface.
Maintains a reference to an object of type Implementor.
RefinedAbstraction (IconWindow)
Extends the interface defined by Abstraction.
Implementor (WindowImp)
Defines the interface for implementation classes. This
interface doesn't have to correspond exactly to Abstraction's
interface; in fact the two interfaces can be quite different.
Typically the Implementor interface provides only primitive
operations, and Abstraction defines higher-level operations based
on these primitives.
ConcreteImplementor (XWindowImp, PMWindowImp)
Implements the Implementor interface and defines its
concrete implementation.