100% found this document useful (2 votes)
14 views

Download Professional Design Patterns in VB NET Building Adaptable Applications 1st Edition Tom Fischer ebook All Chapters PDF

The document promotes the ebook 'Professional Design Patterns in VB.NET: Building Adaptable Applications' by Tom Fischer and others, available for download on ebookgate.com. It includes a comprehensive table of contents covering various design patterns and their applications in different tiers of software architecture. Additional resources and related ebooks are also listed for instant download.

Uploaded by

kagdaweisu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
14 views

Download Professional Design Patterns in VB NET Building Adaptable Applications 1st Edition Tom Fischer ebook All Chapters PDF

The document promotes the ebook 'Professional Design Patterns in VB.NET: Building Adaptable Applications' by Tom Fischer and others, available for download on ebookgate.com. It includes a comprehensive table of contents covering various design patterns and their applications in different tiers of software architecture. Additional resources and related ebooks are also listed for instant download.

Uploaded by

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

Get the full ebook with Bonus Features for a Better Reading Experience on ebookgate.

com

Professional Design Patterns in VB NET Building


Adaptable Applications 1st Edition Tom Fischer

https://ebookgate.com/product/professional-design-patterns-
in-vb-net-building-adaptable-applications-1st-edition-tom-
fischer/

OR CLICK HERE

DOWLOAD NOW

Download more ebook instantly today at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Professional Optical System Design Fischer

https://ebookgate.com/product/professional-optical-system-design-
fischer/

ebookgate.com

Professional ASP NET 3 5 SP1 edition in C and VB Bill


Evjen

https://ebookgate.com/product/professional-asp-net-3-5-sp1-edition-in-
c-and-vb-bill-evjen/

ebookgate.com

Mastering ASP Net with VB Net 1st Edition A. Russell Jones

https://ebookgate.com/product/mastering-asp-net-with-vb-net-1st-
edition-a-russell-jones/

ebookgate.com

Beginning ASP NET 3 5 in VB 2008 From Novice to


Professional 2nd Edition Matthew Macdonald [Macdonald M.]

https://ebookgate.com/product/beginning-asp-net-3-5-in-vb-2008-from-
novice-to-professional-2nd-edition-matthew-macdonald-macdonald-m/

ebookgate.com
Beginning ASP NET 1 1 with VB NET 2003 1st Edition Chris
Ullman

https://ebookgate.com/product/beginning-asp-net-1-1-with-vb-
net-2003-1st-edition-chris-ullman/

ebookgate.com

High Performance Responsive Design Building Faster Sites


Across Devices 1st Edition Tom Barker

https://ebookgate.com/product/high-performance-responsive-design-
building-faster-sites-across-devices-1st-edition-tom-barker/

ebookgate.com

Pro ASP NET SharePoint 2010 Solutions Techniques for


Building SharePoint Functionality into ASP NET
Applications 1st Edition Dave Milner
https://ebookgate.com/product/pro-asp-net-sharepoint-2010-solutions-
techniques-for-building-sharepoint-functionality-into-asp-net-
applications-1st-edition-dave-milner/
ebookgate.com

Building Web Applications with ADO NET and XML Web


Services 1st Edition Richard Hundhausen

https://ebookgate.com/product/building-web-applications-with-ado-net-
and-xml-web-services-1st-edition-richard-hundhausen/

ebookgate.com

Pro ASP NET SharePoint 2010 Solutions Techniques for


Building SharePoint Functionality into ASP NET
Applications 1st Edition Dave Milner (Auth.)
https://ebookgate.com/product/pro-asp-net-sharepoint-2010-solutions-
techniques-for-building-sharepoint-functionality-into-asp-net-
applications-1st-edition-dave-milner-auth/
ebookgate.com
Summary of Contents
Introduction
Chapter 1: Introduction to Design Patterns
Chapter 2: Design Patterns in the Data Tier
Chapter 3: Design Patterns in the Middle Tier
Chapter 4: Design Patterns in the Presentation Tier
Chapter 5: Between the Tiers: Design Patterns and .NET Remoting
Chapter 6: What Next?
Appendix A: UML Primer
Index
Professional
Design Patterns in VB.NET:
Building Adaptable Applications

Tom Fischer
John Slater
Pete Stromquist
ChaurG. Wu

APress Media, LLC


Professional
Design Patterns in VB.NET:
Building Adaptable Applications
© 2002 by Apress
Originally published by Apress in 2002

A l l rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.

ISBN 978-1-59059-274-8 ISBN 978-1-4302-0783-2 (eBook)


DOI 10.1007/978-1-4302-0783-2

Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.

Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth
Avenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co.
KG, Tiergartenstr. 17, 69112 Heidelberg, Germany.

In the United States: phone 1-800-SPRINGER, email [email protected], or visit


http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, email
[email protected], or visit http://www.springer.de.

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,
Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email [email protected], or visit
http://www.apress.com.

The information in this book is distributed on an "as is" basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.

The source code for this book is available to readers at http://www.apress.com in the Downloads
section.
Credits

Editorial Board Commissioning Editor


Dan Appleman Paul Jeffcoat
Craig Berry
Gary Cornell Managing Editors
Tony Davis Viv Emery
Steven Rycroft Laurent Lafon
Julian Skinner
Martin Streicher Project Manager
Jim Sumser Emma Batch
Karen Watterson
Gavin Wray Author Agent
John Zukowski Nicola Phillips

Additional Material Production Coordinator


Richard Blair Sarah Hall
Ian Nutt
Production Assistant
Technical Reviewers Neil Lote
Richard Blair
Maxime Bombardier Cover
Cristof Falk Kurt Krames
Damien Foggon
Mark Horner Index
David Sussman Adrian Axinte
Mike Walston
Proofreaders
Technical Editors Fiona Berryman
Dev Lunsford Chris Smith
Dan Maharry
Ian Nutt
About the Authors

Tom Fischer
Tom Fischer's career spans a broad range of technologies, working with some of the most
prestigious consulting firms in the Twin Cities. His certifications include the Sun Certified Java
Programmer (SejP), Microsoft Certified Solution Developer (MCSD), and Microsoft Certified
Database Administrator (MCDBA).

As a Microsoft Certified Teacher (MCT), Tom also helps teach other developers about the latest
.NET tools and technologies.

I would like to dedicate my contributions to Theresa, Ali, and Kate. They are the greatest! - TF

John Slater
John Slater is a project manager at Management Reports International in Cleveland, OH. At
MRI he is currently developing applications for the property management industry. Right now,
he is working on several projects using .NET development tools and .NET Enterprise servers.

In his free time John enjoys outdoor activities and playing with his children Rachel and Nathan.
He can be reached [email protected].

Pete StromquIst
Pete Stromquist is a consultant at Microsoft Technologies (one of the nation's premier Microsoft
Certified Solution ProViders), specializing in web-enabled application development using
Microsoft tools and technologies. He has spent the last several years architecting and developing
the following types of applications: intranet content management, web-enabled training and
testing software, B2B and B2C e-commerce, and web-based telemetry and logistics. He has
complemented his VB skills with several other technologies such as: XML, XSL, COM+, lIS,
ASP, and of course .NET.

Pete also enjoys teaching and presenting on .NET technologies. He has a Mechanical
Engineering background, and received his Bachelor of Science from the University of Minnesota.
ChaurG. Wu
Chaur Wu currently works for Trend Micro Inc. as a senior software engineer. He started
software programming before he was old enough to qualify for a driving license. The first
program he wrote was a bingo game - in assembly code on an 8051 Single chip. To capitalize on
the program, he ran a small casino in the lab - he developed primitive game boxes that
connected his pals and allowed them to place bets.

He's also been involved in much larger projects. For example, he developed a program in C++
to simulate the movement and geographical coverage of GPS satellites. As a research assistant in
his graduate study, he implemented a wavelet-based video compression algorithm for a traffic
surveillance system sponsored by Boston City Department of Transportation. He also helped
solve a blurred image problem using inverse filters and other image processing algorithms for a
client who designs fiber optics components in San Jose, CA.

His technical interests include distributed software systems inJava, COM, and .NET, generative
programming, software deSign, and neural networks. Outside of work, his favorite vacation combines
a one-night gambling trip to Reno followed by a day of skiing at some resort near Lake Tahoe.

You can email [email protected].

I would like to dedicate my efforts in this book to my two-year-old daughter, Sarah.


-CGW
r - --==
--- ------r-f - ....-.-
.~-~
·
,••
·

-..... .'.
-~.

.0-
Table of Contents

Introduction 1
Who Is This Book For? 2
What Does This Book Cover? 2
What This Book Does Not Cover 3

What You Need to Use This Book 3


Style Conventions 4
Customer Support and Feedback 5
Source Code and Updates 5
Errata 6
forums.apress.com 6

Chapter 1: Introduction to Desl@ Patterns 9


What Is a Design Pattem? 10
Catalogs of Patterns 10
The Gang of Four 10
Other Catalogs and Resources 11
Design Patterns and Visual Basic 11
The Arrival of VB. NET 12
When Should we use Design Patterns? 12
How a Design Pattern can Improve a Design 13
The Actional TakeHomePay Application 13

The Building Blocks 16


Creational Patterns 17
The Singleton Design Pattem 18
The Abstract Factory Design Pattem 21
The Factory Method Design Pattem 26
Structural Patterns 29
The Adapter and Fagade Design Pattems 29
The Bridge Design Pattem 34
The Composite Design Pattem 39
The Decorator Design Pattem 43
The Proxy Design Pattem 49
Behavioral Patterns 51
The Observer Design Pattem 52
The State Design Pattem 55
The Strategy and Template Method Design Patterns 60
Table of Contents

Application of Design Patterns 64


Pattern Selection 64

Summary 66

Chapter 2: Design Patterns in the Data Tier 69


Requirements of a Data Tier 70
A Requirements List 71
Analysing the Requirements 71
Data-Tier Architecture 72
A Simple but Inflexible Data-Tier Example 72
A Slightly More Maintainable Example 74
Creating a Flexible Data Access Framework 75
The .NET Data Providers 75
The .NET Data Provider Objects 76
The Design Patterns Analysis 77

Building the Data Tier 82


A UML Class Diagram 83
Building the Output Classes 84
The Abstract Base Output Classes 84
The Concrete Product Classes 85
Building the Factory Classes 88
The Abstract Factory Class 88
The NWDSARequest Helper Class 89
Managing Connection Strings 92
The Concrete Factory Classes 95
Compiling the Data Tier Application 103
Testing the Data Tier Application 104
A Simple Windows Test Application 104
Building the Application 104
Testing the SQL Server .NET Data Provider 109
Testing the OLE DB .NET Data Provider 109
Testing the ODBC .NET Data Provider 110
A Simple Web Test Application 111
Summary 114

Chapter 3: Design Patterns In the Middle Tier 117


Handling Orders 118
Business Requirements 118
Technology Requirements 119
Analysis and Design 119
Use Case Diagrams 120
Activity Diagrams 121
Homing in on Patterns 122
Sequence Diagrams 124
Class Diagrams 125

ii
Table of Contents

The Decorator Pattern Classes 126


The Strategy Pattern Classes 126
The Final Class Diagram 127

The Coding Part 127


Setting up the Infrastructure 128
Registering Inventory.dll 128
Setting up MSMQ 129
Setting up the SQL Server Databases 129
Creating a Visual Studio .NET Solution 131
The Inventory 131
The Legacy Application 132
The LegacyWrapper 135
The Test Harness 137
Adding the Controls 138
Adding the Code 139
The Middle Tier 142
The ReceiveDocument Application 142
The ProcessDocument Application 153
Document Processing with the Decorator Pattern 154
The Business Rules 160
The Processing Manager - the OrderManager Class 169
OrderManagement 172
The SimpleQueueManager Class 172
The Place Class 173
System Testing 174

Summary 175

Chapter 4: Design Patterns In the Presentation Tier 177


The Problem with the Presentation Tier 177
Introducing Model/View/Controller 178
MVC in a Nutshell 179
The Power of MVC 180
Decoupling the Model and the View 181
Decoupling the View and the Controller 181
The Design Patterns Used in MVC 182
MVC in VB6 183
VB6 MVC Class Diagram 183
The Model Class 184
The View Class 185
The Controller Class 185
Running and Analysing the Application 186
Is It Worth It? 187
MVC in VB.NET 187
Inherited Forms 187
ASP.NET Web Forms 190
ASP.NET Server Controls 190
Event Handling and Delegates 190
Multithreading and Asynchronous Programming 191

iii
Table of Contents

Building an MVC Framework for .NET 191


The MVC Framework Class Diagram 192
A Simple MVC Class Diagram 192
Incorporating the MVC Class Diagram into .NET 193
The MVC Framework Class Schema 201
Views Calling Other Views 204
MVC Framework Code 209
The Model 210
The View 210
The Controller 213

A Front End for Northwlnd Order Processing 214


Use Case Diagrams 215
Activity Diagrams 215
A Common NOP Model 216
The NOPData Class 217
The Orders Class 220
The Order Class 220

Concrete Views and Controllers 222


NOPWin for the Sales Reps 222
The NOPWin Class Diagram 222
The OrdersVlew View 223
The OrdersControlier Class 226
The OrdersControlierFactory Class 228
The OrderView View 228
The OrderControlier Abstract Class 230
The NormalOrderControlier Class 232
The SpecialOrderControlier Class 232
The OrderControlierFactoryClass 233
NOPWin Startup 234
NOPWeb for the Customers 235
The NOPWeb Class Diagram 236
The OrdersView View 237
The OrdersControlier Class 241
The ControlierFactoryWebBase Class 242
The OrdersControlierFactory Class 243
The OrderView View 243
The OrderControlier Class 247
The NormalOrderControlier Class 249
The SpecialOrderControlier Class 249
The OrderControlierFactory 250
The Anished NOPWeb Application 250

Summary 252

Chapter 5: Between the Tiers: Design Patterns and .NET Remotlng 255
.NET Remotlng - A Primer 256
Remoting Objects and the Host Server 256
Channels and Protocols 257

iv
Table of Contents

The Client, the Proxy, and the soapsuds.exe Utility 257


The Configuration File, Default.cfg 257

A Call Event Coordinator Example 258


System Requirements 258
The Players in the System 258
The Tiers of the System 259
The Development Phases of our Application 260

Phase 1 - The Basic Application 260


Collecting and Distributing Calls 261
Recalling the Observer Pattern 261
Taking Advantage of the Event and Delegate 263
Building the Application 263
The Remote Notifier Object (EventCoordinator) and the Delegate 264
The Remote CSR Server Object 267
The Host Applications 269
The Client Application 272
Running the Example Application 274
A Note on the Proxy Pattern 275

Phase 2 - Asynchronous Call Handling 276


The Asynchronous Programming Pattern 276
Understanding the Pattern 276
Amending the Application 278
Building and Running the Example 280
Phase 3 - Flexible Policy Management 281
Adjusting the Application Design 281
Considering a Design Pattern Solution 282
Deciding on the Decorators 284
Amending the Representative Class Library 286
The PolicyDecorator Class 286
The IDPolicyDecorator Class 287
The AreaPolicyDecorator Class 288
The Configuration File, Default.cfg 289
Building a Client Program 290
The Configuration File, Default.cfg 292
Building and Running the Example 293
Summary 294

Chapter 6: What Next? 297


Refactorlng 297
Extract Class 298
Parameterize Method 299

Antlpatterns 300
The Antipatterns Bible 301
The Blob 301
Lava Row 301
Poltergeists (aka Proliferation of Classes) 302

v
Table of Contents

Golden Hammer 302


Avoiding Antipatterns 302

Resources and Further Reading 303

ARRendlx A: UML Primer 307


A Typical Development Process 308
Project Stages and UML Tools 308

The Use Case 310


A Sample Use Case 310
The Extends Relationship 315
The Includes (or Uses) Relationship 315
Applying Use Cases 316

The Class Diagram 316


Associations 317
Attributes and Operations 320
Aggregation and Composition 321
Interfaces 323
When to use Class Diagrams 323

The Activity Diagram 324


Starting State and Final State 325
Branches 325
Swimlanes 326
When to use Activity Diagrams 326
Interaction Diagrams 327
The Sequence Diagram 327
When to use Sequence Diagrams 330

The State Diagram 330


When to use State Diagrams 331

Physical Diagrams 331


The Component Diagram 332
The Deployment Diagram 332
When to use Physical Diagrams 333

Summary 334

vi
Table of Contents

vii
r ---!:.::-=
~
- -- -~-JI-f~--~
-~~·------·-·----
;

:r-l_.'~- ··-·--"~'-~~--~=
;
: .•
~

·• ==1Tfu_,_·_~.._..-~-_-~~~l,.
_--
:
---'-- · ... _
f::/lii~:~::'-;-~··:-T -~~
.."- '. < •... - - _ . :
-:~~·:~L:~:L_
_ _I
".
:
:
··i
.

, :
.. -.-. .-.
Introduction

It is perhaps easiest to think of a design pattern as a template for a solution. When presented with a
problem, the first thing we do is identify the defining characteristics of the problem. Then, we examine
our armoury to see whether we have a generic solution that solves the problem we've characterized. If
so, we apply the solution template and hence solve the problem.

The design pattern itself describes both the defining characteristics of the problem and the
characteristics of the solution. The solution template is tried and tested, which means that once we've
correctly identified which pattern to use, we can apply it without the need to do research and proof-of-
concept testing.

This process is one that applies in all walks of life - architecture, medicine, furniture restoration ... Not
all disciplines use the term "design pattern", but in any case the process is the same. This book is about
design patterns in object-oriented programming (OOP).

So, a design pattern in OOP is a solution template - it describes the characteristics of the problem and of
the solution, but leaves you {the developer} to implement the details of the solution. Design patterns are
not about programming "tricks"; rather, they penetrate to the heart of the problem at hand, and allow
you to break things down into constituent parts. Design patterns help you see the path toward the
overall solution, without dictating it.

This book draws on the work of the Gang of Four {or GoF} - Erich Gamma, Richard Helm,
RalphJohnson, and John Vlissides - whose seminal book Design Patterns: Elements o/Reusable Object-
Oriented Software {Addison-Wesley, ISBN 0-201-63361-2} describes the fundamentals of design patterns
in OOP and catalogs 23 design patterns in significant detail.
Introduction

Design patterns rely on true 00 capability in the production language. Unlike previous incarnations of
Visual Basic, VB.NET is truly object-oriented and requires a rather different mindset. In this book we
will put the focus on using design patterns with VB.NET, and on how to put the GoF patterns (and other
patterns) to use in that context.

Who is This Book For?


This book is primarily targeted at developers and architects who wish to see discussion and functional
examples of design patterns, coded in VB.NET. The concepts behind design patterns are language-
independent; therefore, the concepts described in this book can be applied in any truly object-oriented
language. The book's examples are all coded in VB.NET.

The book does not assume that you have any knowledge of design patterns, but it does assume
familiarity with Visual Basic .NET. Some knowledge of OOP and/or UML will also help the reader to
appreciate this book, because most of the design patterns are built on 00 principles and described
using UML diagrams.

This book does contain a UML Primer (in Appendix A), and thus is not intended to exclude readers who
are not well-versed in OOP and UML. For those readers, this book uses UML to describe some
fascinating and generic applications of 00 principles, and should make a good companion to a "first
principles" book on OOP or UML. We do not explain the basics of OOP or UML during the course of
the chapters themselves - instead, we expect that the reader is already armed with some experience or
is willing to fill in the gaps.

This book is also targeted at:

Cl Readers who are familiar with VB.NET and wish to use 00 techniques like design patterns to
get more from the language and from their application architecture
Cl Readers who have seen the GoF Design Patterns book, and wish to see some of the GoF
patterns and other patterns demonstrated in VB.NET
Cl Readers who have tried implementing design patterns in Visual Basic, and wish to learn how
the true 00 nature of VB.NET makes the whole thing much easier

This is a fundamentally practical book, and for the VB.NET developer it makes a good companion to
the more theoretical GoF Design Patterns book.

What Does This Book Cover?


Chapter 1 begins with a definition of design patterns, and a discussion of what design patterns mean to
VB and VB.NET programmers. It also contains working demonstrations of about a dozen of the GoF
design patterns, with commentary and comparison.

In Chapters 2-4, we examine three case studies, each of which examines the role of design patterns in
one of the three tiers of a classical 3-tier application. Chapter 2 takes the data tier, Chapter 3 takes the
middle (business logic) tier, and Chapter 4 takes the presentation tier. These case studies provide us
with a number of lessons. For example:

2
Introduction

OWe discuss the process of recognizing the characteristics of a design pattern within a given
problem, and hence design a solution architecture that is based on that pattern
OWe examine implementations of GoF patterns and other patterns (in isolation and in
combination)
OWe look at how to translate patterns into code
o We highlight the advantages gained by applying patterns to particular problems

Although they are similar, each of these case studies is a stand-alone study designed to focus on the
relevance and implementation of design patterns in the context of one particular tier.

To complement the main three case studies, Chapter 5 examines .NET Remoting - a candidate
technology for tying together the distributed tiers of a .NET application. Chapter 5 is not an
introduction to .NET Remoting, but looks at the subject of .NET Remoting from a design patterns point
of view. In it, we look at how design patterns have been built into the principles of .NET Remoting from
the start, and how .NET Remoting also supports the developer who uses design patterns in his remoting
implementations.

Chapter 6 rounds off the book by suggesting some related areas and subjects that follow on naturally
from a study of design patterns. It also includes a selection of resources, references, and further reading.

What ThIs Book Does Not Cover


This book is not a catalog of design patterns. Rather, its subject is the application of design patterns in
real world scenarios. During the course of the book, we will discuss most (although not all) of the GoF
patterns. We will also make use of some other non-GoF patterns (such as Store and Forward,
Model/View/Controller, and Asynchronous Programming).

The book also does not teach VB.NET, OOP, or UML; it is assumed that the reader has some
familiarity with these subjects or is willing to fill in the gaps where necessary. However, as we've already
mentioned, there is a UML Primer contained in the back of the book, in AppendiX A - this is intended as
a qUick tutorial or reference in UML.

What You Need to Use This Book


The examples in this book are coded in VB.NET. If you wish to build the examples for yourself, then
you will need some or all of the following:

o A suitable operating system. Either Windows 2000 Professional, Server or Advanced Server
Edition (at the time of writing, the latest service pack is SP2), or Windows XP
Professional Edition.
o The .NET Framework SDK.
o In Chapters 1-4, we use the Visual Studio .NET IDE to build and compile applications. In fact,
VB.NET ships with both the .NET Framework SDK and Visual Studio .NET; it is possible to
buiild and compile these applications without VS.NET, using the command-line tools that ship
with the .NET Framework SDK. We use the command-line compiler only in Chapter 5.

3
Introduction

o Chapters 2 and 3 make use of a SQL Server 2000 database server. If you don't have access to
a SQL Server installation, you can run the examples using the SQL Server Desktop Engine
(also known as MSDE).

MSDE is shipped with the .NET Framework SDK, and also with VS.NET. To install it, execute
the file InstMSDE.exe (which is found in the IProgram FileslMicrosoft.NET
IFrameworkSDKlSampleslSetuplMSDE folder). MSDE does not offer the same admin tools as
Sf& Server, but there are some useful command-line utilities detailed in the file
IProgram FileslMicrosoft.NEnFrameworkSDKISampleslSetuplhtml
IConfigDetails.htm. Moreover, note that VS.NET provides an arguably better UJ to a SQ,L
Server database.
o Chapter 3 makes use of a "legacy" class library application. We provide both the source code
and the compiled DLL for this application. You don't need to build it yourself. However, if
you want to compile the DLL for yourself, you'll need Visual Basic 6.0 to do it.
o Chapter 5 makes use of MSMQ, and Chapters 2 and 4 make use of lIS 5.0. These Windows
Components ship with all versions of Windows 2000 and also with Windows XP Professional
Edition. Some editions do not install MSMQ and lIS as part of the default OS installation -
you can install them manually from the Control Panel I Add/Remove Programs dialog.

Style Conventions
We have used certain layout and font styles in this book that are designed to help you to differentiate
between the different kinds of information. Here are examples of the styles that are used, with an
explanation of what they mean.

As you'd expect, we present code in two different ways: in-line code and displayed code. When we need
to mention keywords and other coding specifics within the text (for example, in discussion relating to an
if . . . else construct or a class or object) we use the single-width font as shown in this sentence. If we
want to show a more substantial block of code, then we display it like this:

Public Shared Function GetInstance() As MySafeSingleton


If m_Instance Is Nothing Then
rnLInstance = New MySafeSingleton()
End I f
Return rnLInstance
End Function

Sometimes, you will see code in a mixture of gray and white backgrounds, like this:

Public Shared Function GetInstance() As MySafeSingleton


m_Mutex.WaitOne()
If m_Instance Is Nothing Then
rnLInstance = New MySafeSingleton()
End I f
m_Mutex.ReleaseMutex()
Return m_Instance
End Function

4
Introduction

In cases like this, we use the gray shading to draw attention to a particular section of the code - perhaps
because it is new code, or it is particularly important to this part of the discussion. We also use this style
to show output that is displayed in the console window.

Advice, hints, and background information comes in an indented, italicized font like this.

[mportant pieces of information (that you really shouldn't ignore) come in boxes like this!

Bulleted lists appear indented, with each new bullet marked as follows:

o Important Words are in a bold type font.


o Words that appear on the screen, or in menus like the File or Window, are in a similar font to
the one you would see on a Windows desktop.
o Keys that you press on the keyboard like ctrl and enter are in italics.

Customer Support and Feedback


We value feedback from our readers, and we want to know what you think about this book: what you
liked, what you didn't like, and what you think we can do better next time. You can send us your
comments by [email protected]. Please be sure to mention the book's ISBN and title in
your message.

Source Code and Updates


As you work through the examples in this book, you may choose either to type in all the code by hand,
or to use the source code that accompanies the book. Many readers prefer the former, because it's a
good way to get familiar with the coding techniques that are being used.

Whether you want to type the code in or not, it's useful to have a copy of the source code handy. If you
like to type in the code, you can use our source code to check the results you should be getting - they
should be your first stop if you think you might have typed in an error. By contrast, if you don't like
typing, then you'll definitely need to download the source code from our web site! Either way, the
source code will help you with updates and debugging.

Therefore all the source code used in this book is available for download at http://www.apress.com.
Once you've logged on to the web site, simply locate the title (either through our Search facility or by
using one of the title lists) . Then click on the Source Code link on the book's detail page and you can
obtain all the source code.

The files that are available for download from our site have been archived using WinZip. When you
have saved the attachments to a folder on your hard drive, you need to extract the files using a de-
compression program such as Win Zip or PKUnzip. When you extract the files, the code is usually
extracted into chapter folders.

5
Introduction

Errata
We have made every effort to make sure that there are no errors in the text or in the code. However, no
one is perfect and mistakes do occur. If you find an error in this book, like a spelling mistake or a faulty
piece of code, we would be very grateful to hear about it. By sending in errata, you may save another
reader hours of frustration, and of course, you will be helping us provide even higher quality
information.

To find known errata and submit new errata, simply go to the appropriate book page on the Apress
website at http://www.apress.com.

forums.apress.com
For author and peer discussion, join the Apress discussion groups. If you post a query to our forums, you
can be confident that many Apress authors, editors, and industry experts are examining it. At
forums.apress.com you will find a number of different lists that will help you, not only while you read
this book, but also as you develop your own applications.

To sign up for the Apress forums, go to forums.apress.com and select the New User link.

6
Introduction

7
... -
~.~

-_-
.. . -.
.... -
Introduction to Design Patterns

In the time since developers first began to apply object-oriented techniques, something quite fascinating
has occurred. As the development community gained a better and better understanding of the
implications of OOD, it became increasingly obvious that certain types of problem were appearing over
and over again - and that similar types of problem could be solved using similar types of solution.

Around the world, experienced software engineers were independently finding that they could
recognize certain specific structural (and object-related) requirements in their project design. Moreover,
each time they recognized a certain requirement, they could apply a certain object pattern to achieve
the required solution.

Over time, and by its very nature, 00 programming has spawned a common set of recognizable
problems and solutions. Thus, when a developer begins to design an application and discovers certain
problems or structures are required, they often find that that type of problem or structure has already
been identified elsewhere, and that a suitable, well-tested solution already exists.

This phenomenon has earned its own nickname - design patterns. In this chapter we will present an
introduction to design patterns by tackling the subject from three different angles:

o First, we'll take a look at what design patterns are, and what they mean to Visual Basic developers.
o Second, with the help of a fictional payroll application, we'll compare two designs and see
how the use of a design pattern can improve a VB. NET application.
o Finally, we'll explore some basic design patterns - focusing in particular on some very
common patterns and some that are relevant to this book.
Chapter 1

What is a Design Pattern?


Essentially, a design pattern is a combination of two things: a description of a problem and a description
of its solution. It describes the problem in terms of its defining characteristics, and then describes the
solution in terms of the elements involved, how they work together and what they do.

Design patterns are used in many walks of life. In Town Planning and Architecture, design patterns are
used to describe the characteristics of generic problems in civic and building design, and standard solution
patterns that can be applied to the problem in order to solve it. The challenge of civic designers and
architects is to recognize the patterns in real life problems, match them up to the theoretical problems of
one of the standard design patterns, and then solve the problem by applying the prescribed solution.

Note that the solution doesn't describe details of a particular implementation. Instead, it is like a
template: it describes all the necessary elements and characteristics of the solution in generic
language, and forms the basis for many implementations.

In this book, we're thinking about the concept of design patterns as applied to object-oriented programming
(OOP). In the OOP context, the principles of design patterns are similar. Each pattern consists of:

o A description of a common programming problem, stated in general terms.


o A description of a tried and tested solution to the problem. The solution is in template form,
describing each of the participating classes, the roles and responsibilities they have, and their
relationships to one another.

For the programmer involved in an 00 analysis and design task, the challenge is to recognize each
generic problem pattern in their project, match it to an established design pattern, and apply the
solution template to their project within their project design.

Catalogs of Patterns
This leads us to the question of where design patterns come from. Is there a definitive list of design
patterns that no 00 programmer should be without?

It's probably impossible to produce an exhaustive list of all possible design patterns, but as time goes
on, it gets harder and harder to find new, fundamental ones. While this is an interesting academic
challenge in its own right, the real purpose of design patterns is to help us build applications, and over
recent years, many of the most common patterns have been identified and documented.

There is one particularly important and famous work in this area, which we'll meet in this section.

The Gang of Four


In the early 1990s, this new design practice was taking the software building business by storm. There
was a proliferation of technical papers, conferences and communities that provided vehicles for
programmers to exchange their latest ideas and patterns. But at first, as in any new science, information
was not well cataloged or easily consumed. In 1994, four people - Erich Gamma, Richard Helm, Ralph
Johnson, andJohn Vlissides - remedied that deficiency. They wrote what would become the pattern
"bible" - Design Patterns, Elements ofReusable Object-Oriented Software (Addison-Wesley, ISBN 0-201-
63361-2). The success of this book earned them the affectionate nickname, the Gang ofFour (or Go}) -
and the patterns described in the book are often referred to as the GoF patterns.

10
Introduction to Design Patterns

The GoF's Design Patterns book catalogs 23 design patterns. They're not just a bunch of ideas that piqued
the authors' interest. These patterns represent a collection of design motifs that occur regularly in many
well-built object-oriented applications. For example, their Adapter pattern constitutes a blueprint for
converting the interface of an existing class into a different one with minimal effort. Any software
engineer who knows about the Adapter pattern knows that there is at least one tried-and-tested way to
accomplish this task without proto typing or proof-of-concept testing.

Each GoF pattern is given in terms of:

o A statement of the problem, in generic language, in the form of the pattern's intent, its
motivation, and its applicability.
o A description of the solution, in terms of its structure, a list of its participants and the
collaborations between them, the consequences of applying the pattern, implementation notes,
some sample code, some known uses and a list of related patterns.

Other Catalogs and Resources


The 23 GoF patterns are not the only 00 design patterns in existence. However, this book does form the
single largest printed catalog of design patterns. There are many other references on the Web that you may
find helpful when looking for more information. The list of web sites below is by no means exhaustive:

http://www.cetus-Iinks.org/oo_patterns.html- An excellent listing of other links


http://hillside.netlpatterns/ - The unofficial "home" of the patterns community
http://c2.com/cgi-bin/wiki - Another unofficial "home" of the patterns community
http://www.xmlpatterns.com/- Patterns for XML (these are definitely not GoF patterns!)
http://www.dofactory.com/patterns/patterns.asp - This site is written for C# programmers,
but the principles are all translatable into VB.NET

Design Patterns and Visual Basic


Despite the general applicability of design patterns, the capabilities of the underlying target language
are very important. In their Design Patterns book, the GoF demonstrate their ideas using C++ and
Smalltalk - and both of these languages are about as object-oriented as a production language can be.

In fact, this is indicative of an important consideration when applying design patterns in an object-
oriented environment: namely, that the production language must be truly object-oriented. The reason
for this is that 00 design patterns are built on the foundations of 00 theory - abstraction,
encapsulation, polymorphism, and (implementation) inheritance. If your intended target language is one
that lacks the key features associated with true object-oriented development, then this jeopardizes your
chances of being able to apply a pattern in that language.

This presented a problem to anyone who wanted to apply design patterns to Visual Basic application. No
version of Visual Basic (up to and including version 6.0) is truly object-oriented - in particular, VB does
not directly support implementation inheritance. The task of employing patterns in VB is tedious at best,
and any VB6 application that relies on a complex inheritance scheme requires quite a few workarounds.

11
Chapter 1

The Arrival of VB.NET


Given this situation, it is easy to see why most Visual Basic developers were inclined to snub design
patterns. While many recognized the benefits that design patterns brought to the design table, the
complexity and risk involved with shoehorning the resulting designs into a Visual Basic application
negated these benefits. Experienced Visual Basic developers did the cost/benefit analysis and found that
design patterns did not pay.

The arrival of the .NET Framework and VB.NET has dramatically changed the analysis. VB.NET is
truly object-oriented, and therefore is a good choice of production language for 00 applications whose
designs are based on design patterns.

Overnight, Visual Basic developers have acquired one of the most powerful object-oriented languages
there is. However, they've also discovered that migration from VB6 to VB.NET is more difficult than
their migrations to earlier versions of VB. While they're armed with a mastery of strange API calls and
undocumented tricks, this doesn't provide much insight into crafting sound object-oriented applications.
VB.NET programming requires a shift in mindset, to accompany the more object-oriented nature of
the language.

Fortunately, the wealth of activity that was directed at other 00 languages now provides some answers
for the VB.NET programming community. From the work done to support the application of design
patterns in languages like C++ and Smalltalk, there is a huge body of lessons learned and best practices
in the form of design patterns in all 00 languages.

When Should we use Design Patterns?


Sometimes, it is difficult to evaluate whether it's worth using design patterns in a particular situation -
that is, when the application of design patterns will constitute a net gain. Like the VB6 developers who
avoided design patterns because it was difficult to shoehorn the results into their chosen language, there
are situations in which design patterns aren't right.

It's probably helpful to list some situations in which a developer might not want to use design patterns.
After all, you wouldn't want to use a tool that adds a level of complexity unless it gives you some
discernable benefit. If any of the following applies to your current situation, then you might find that it's
not suitable to try to apply design patterns within that project:

o When the application being built today will not change, the code accurately captures all
requirements, and there are no planned enhancements or features. The application you're
building will be the first and last release. (Yeah, right.)
o Your application's code requirements are unique. No software engineer has ever built
anything like it. The program does not deal with any of those routine issues like object
creation and event notification. (Just what does it do, then?)
o There is plenty of time to prototype all of your new design ideas. Alternatively, you are so
confident of your ideas that they do not require any proof-of-concept testing.
o Everyone on your team has worked together for twenty or so years. If you ask Bill to try the
"thing-a-ma-jig" trick, he knows exactly what to do. The team already possesses a common
design vocabulary, so you don't need to learn someone else's.

12
Introduction to Design Patterns

If your situation is described in any of the above, please pass this book on to a friend. Otherwise,
keep reading.

There are two questions to keep in your head when you're trying to work out the value of design
patterns in your project. First, can you justify the presence of the pattern, even when you consider the
extra complexity and potential performance hit that it brings? Second, will the added value of a proven
design and lower maintenance bills cover the upfront investment?

How a Design Pattern can Improve a Design


Before we begin to step through our description and examples of some of the GoF patterns, let's look at
a sample of the design work surrounding a fictitious payroll application. We'll look at two different
design proposals: one ofthem employs a design pattern, and one does not. We'll see how the one with
the design pattern turns out to provide a significantly more extensible and flexible design.

The Fictional TakeHomePay Application


The preliminary requirements have been gathered for the WantaBeBig Corporation's new "Take Home Pay
Calculator" application, hereafter known as TakeHomePay. WantaBeBig has invited two software companies
(N and P) to propose designs for the application, and each hopes to win the coding phase contract.

WantaBeBig have specified that the target language for the application is VB.NET. They have not stated
any application design expectations.

In a requirements document, they have:

CJ Outlined that the purpose of the TakeHomePay application is to estimate the amount of
money that a WantaBeBig employee can expect to see in their next paycheck, immediately
after submitting timesheets
CJ Stated that calculating this amount would involve several complex calculations, based on
varying country taxes, local taxes, and retirement plan contributions
CJ Included details of all of the business rules for these cumbersome calculations
CJ Noted that WantaBeBig currently operates in London and New York City and may open up
other offices over the next few years
CJ Predicted that the Personnel Manager had plans for the introduction of a second retirement plan

Unsurprisingly, the lead architects of the two consulting companies take different approaches. One
architect designs TakeHomePay in the style of a number of previous applications that his team had built
using Visual Basic 6.0. The other architect, with similar experience, elects to employ some recently
acqUired pattern knowledge in his design. We'll look at each of these designs in turn.

The Non-Pattern Design


Since the lead architect at Company N had constructed a payroll-like application before, he takes little
time modeling the application. He produces the following object model:

13
Chapter 1

1TakeHomePay I
IGetTakeHome() I
'I
I I
IUKlondonTaxNoRetlrement ! IU5NYCTaxNoRetirement I
LGetTakeHomeO I IGetTakeHomeO I
I
IUKlondonTaxRetlrement! IUSNYCTaxRetlrement I
LGetTakeHomeO I I GetTakeHomeO I

This figure is a standard UML class diagram. Ifyou're not sure how to translate it, or ifyou would
appreciate a qUick UML refresher, please refer to the UML Primer in the Appendix A.

The design is simple and straightforward, and contains just five classes in total:

o The main driver class, TakeHomePay


o Four supporting classes (representing the two offices and the fact that an employee either
belongs to the retirement plan or doesn't)

The Pattern DesIgn


As it turned out, the lead architect at Company P has also built payroll applications in the past. But he is
worried. He doesn't like the idea of creating a bunch of specialized classes to handle every combination
of country, locality, and retirement option for an employee. Moreover, he is concerned about the
potential for new offices and retirement plans! After considerable thought, he thinks that maybe a
design pattern known as Decorator could be used to manage the required functionality of the
TakeHomePay application - and it will also be able to cope with additional requirements in the future:

CommonTakeHomePay
GetTakeHomeO

14
Introduction to Design Patterns

If you're curious about how the Decorator pattern works, but you don't want to jump ahead, you'll be
pleased to know that the mechanics of this pattern are surprisingly simple. All of the derived classes
from Decorator operate on a concrete object (CommonTakeHomePay in this example) that gets passed
around like a hot potato. For example, an instance of a CommonTakeHomePay object might first be
passed as a parameter into LondonTax. That entire object could then be passed as a parameter into
UKTax, and so on. Throughout the entire process, the derived class objects (UKTax, LondonTax, etc.) all
operate on the single original CommonTakeHomePay object.

A Change In the Requirements


After the software consulting companies submitted their proposals, the WantaBeBig Company started
offering a second retirement plan and opened an office in Miami. They decide that, in the light of this
business development, it would be foolish to award the TakeHomePay contract immediately. Instead,
they ask the consulting companies to resubmit their designs in the light of the new information.

Both lead architects decide simply to extend their existing designs to take in the new structure. At
Company N, the lead architect finds that he can model the new requirements like this:

ITakeHomePay I
I GetTakeHomeO I
Lf'
I

IUKLondonTaxNoRetlrement I IUSNYCTaxNoRetlrementl t USMlamlTaxNoRetlrement I


I GetTakeHomeO I IGetTakeHomeO I I GetTakeHomeO I
IUKLondonTaxRetlrementA I IUSNYCTaxRetlrementA I IUSMlamlTaxRetlrementA I
LGetTakeHomeO I I GetTakeHomeO I IGetTakeHomeO I

IUKLondonTaxRetlrementB L
LGetTakeHomeO I
IUSNYCTaxRetlrementB I
I GetTakeHomeO I
I IUSMlamlTaxRetlrementB I
IGetTakeHomeO I

As you can see, they have to add no fewer than five new classes to the existing design. There is still one
main driver class, TakeHomePay; but now there are nine supporting classes (representing the three offices
and the fact that there are now three retirement plan options - A, B and none). It's becoming clear that
further additions to the business empire will cause rapid growth in the size of this object model.

At Company P, lead architect finds that his revised model is almost identical to the original:

15
Chapter 1

CommonTakeHomePay
GetTakeHomeO

RetlrementPlanA
GetTakeHomeQ

NYCTax MiamlTax
GetTakeHomeO GetTakeHome()

One of the objects represents the new Miami office, and the other represents the new retirement plan.
This is clearly a more extensible design.

Which Design Won the Contract?


The difference in the ability of each design to handle additional requirements is dramatic. The pattern-
based design only needed two new classes, while the non-pattern design experienced a type of "class
multiplier" effect.

Which TakeHornePay application would you want to build or maintain? The choice is between one with
a sophisticated pattern-based architecture and one with an astronomical number of classes. Of course,
most experienced Visual Basic developers could think of several improvements for the non-pattern
design. But why bother? The Decorator pattern already solved the problem.

Remember, too, that this wasn't an exercise in finding the best way to tackle this particular problem, but
a demonstration of how a pattern could make a profound difference in the ability of your solution to
adapt to changing requirements. We'll return to this example later in this chapter, and give an
implementation of the TakeHornePay application using Company P's Decorator-based design.

Now that we've seen an example of patterns in action, let's take a tour of the different patterns
documented by the GoF.

The Building Blocks


In their Design Patterns book, the GoF classified their 23 patterns into three broad categories: creational
patterns, behavioral patterns, and structural patterns. Within these categories, each of the patterns has
a name that is chosen to reflect the purpose of the pattern. The names of the patterns and their
categories provide designers with a useful handle for thinking about which type of pattern may solve a
particular high-level problem. For example, if you need a pattern that describes object creation, then
you're likely to need one of the five creational patterns.

In this section we're going to take, as a starting point, these three categories of patterns. We'll explain
the common characteristics of each category, and we'll examine in more detail some of the most
commonly used patterns in each category.

16
Introduction to Design Patterns

As I mentioned earlier, the GoF describe each pattern by using a standard template. (That is, they state
the problem in terms of the intent, motivation, and applicability, and the solution in terms of structure,
participants, etc.) This template is based on standards for documenting and describing designs that have
been developed over years; while it borders on being academic in nature, its features are useful without
exception. In particular, the intent constitutes a brief and insightful synopsis of the pattern. Here, for
each pattern we discuss in depth, we'll include a statement of the GoF's intent for that pattern quoted
from their Design Patterns book.

Note that we won't examine a1l23 of the GoF patterns in depth. The aim of this book is not to cover
ground that has already been laid by Design Patterns, but to help put things into a VB.NET perspective
with real examples. Once you've seen these more common patterns in action, you will be well equipped
to investigate and appreciate the others.

Running the Examples In this Chapter


All the code for this chapter is contained in a Visual Basic .NET console application called
Wrox. ProDPA6 9 8 5. ChO 1. Each pattern's demonstration code resides in its own VB file, executed via a
Main routine on that file.

To execute the demonstration for a pattern, open the Wrox. ProDPA6985. ChOl solution in Visual
Studio .NET. View the properties for the project (by typing Shift+F4) and set the corresponding module
as the Startup object. For example, if you set the Startup object to Singleton, as shown below, and then
execute the application, it will run the Main routine that demonstrates the Singleton pattern:

r~ .PYoOPA6985.0.:1I
~1'ypO, ~ ob)ed:
1"-,,
Referl!lnCe Path ;:'lconsoIe
~':':AppIc-:-otlon-'---3"'
. rr::SIn;jeton""7':'--'--:-::':'~-~-~-~-~-~
--:-::13
~DeI_
Roct_o: ~
C""'~otlon Propettlos IWro•. ProDl'A6985.ChOI

WOtIMtIoo
Proloct fold." C:\ProJo<ts\Wrox.PYoOPA6985.ChOI\
ProJo<t"-, Wr... Prolll'A6965.ChOI.'ll>prO!
0UjU MIllO' Wrox.Prolll'A6985.ChOI._

Help

Let's start our discussion with the family of creational patterns.

Creational Patterns
Creational patterns make applications less dependent on the vagaries of simplistic object construction
and class referencing. They provide a more flexible approach towards the four W s of object creation -
Who, What, Where, and When.

17
Chapter 1

Two of the creational patterns we discuss - Abstract Factory and Factory Method - exemplify the
subtlety and difficulty of properly applying patterns. Their names are similar, and fundamentally they
do the same thing - they both create objects. However, it's how each pattern achieves its task that makes
all the difference. Abstract Factory uses objects to manage object creation, while Factory Method relies
on class inheritance to create the right object.

The GoF cataloged five creational patterns: Abstract Factory, Builder, Factory Method, Prototype, and
Singleton. We'll be covering the Singleton, Abstract Factory, and Factory Method patterns.

The Singleton Design Pattern

GoF Intent: Ensure a clas only ha one instance, and provide a global point of access to it.

The most humble of patterns, Singleton ensures that an application creates exactly one instance of the
class in question. One classic application of Singleton is the management of scarce database connections
- this was particularly true before the advent of built-in pooling. Many other applications are still
relevant today - including the management of printer objects and TCP/IP connection objects.

In the old days of Visual Basic 6.0 and earlier, VB did not support explicit object creation. Instead, VB
hid object creation and developers were usually forced to control object creation with the aid of class
events and global variables. With the advent of VB.NET, the days of implicit object creation are gone.
We now have an accessible New constructor method, and this means that we can employ the Singleton
pattern in our VB.NET code.

In fact, the introduction of the default constructor into VB.NET is more than an object-oriented
nicety. One leading cause ofVB6 bugs was the fact that developers could not always control object
creation. In particular, problems arose when declaring a variable using the New keyword, like this:
Dim objSomeObject As New SomeObject
In such circumstances, the developer could never be certain if or when the Visual Basic runtime
engine instantiated the object.
Singleton is so simple that a diagram doesn't help to explain it. The mechanics are straightforward:

1. Hide the default class constructor

2. Add a shared member referencing the solitary, instantiated object

3. Create a public function that creates/returns the referenced object

To emphasize the importance of applying design patterns accurately, let me recount a little story. A
programmer once implemented his own Singleton-like pattern by ignoring Step 3 and using the
default constructor instead. The idea made sense, and to a point, it worked. Only one problem -
each execution ofNew meant that a second instance of the class would be created!
The moral ofthe story is that you should think twice before reinventing the wheel. One ofthe benefits of
using an existing design pattern is that its consequences are known and documented. As soon as you
change the specification ofthe design pattern, you can no longer be sure ofthe behavior and consequences.

18
Introduction to Design Patterns

An Example
Here's an example of a class called MySingleton, which is implemented using the Singleton design
pattern. The default constructor, New (), has been hidden (by making it Private). The Shared
member, ffi_Instance, represents the single shared instance of the object, and the public function
Getlnstance () returns the object reference (but only creates it if it doesn't already exist):

Public Class MySingleton


, Private members
Private Shared mLInstance As MySingleton
Private Shared m_TimeOfBirth As String

, Private New constructor


Private Sub New()
Console.WriteLine("Creating Singleton at " & Now. ToLongTimeString)
m_TimeOfBirth = Now.ToLongTimeString
End Sub

, Public method for "creating" the instance


Public Shared Function GetInstance() As MySingleton
If m_Instance Is Nothing Then
mLInstance = New MySingleton()
End I f
Return m_Instance
End Function

, Public property
Public ReadOn l y Property TimeOfBirth() As String
Get
Return m_TimeOfBirth
End Get
End Property
End Class

Just because New is not publicly unavailable, this doesn't mean we don't need to create a MySingleton
object instance. The trick is to make sure that Getlnstance only creates it when the object does not exist!

Here's a little routine to show the design pattern in action. We create two object variables, objTestl
and objTest2, and use our public Getlnstance () method to instantiate them:

Sub Main ()
Dim objTestl As MySingleton
Dim objTest2 As MySingleton
Dim i As Integer

, call GetInstance()
objTestl = MySingleton.GetInstance()
Console . WriteLine('GetInstance() called at " &
Now . ToLongTimeSt r ing & " ; " &
"objTestl . TimeOfBirth() =" &
objTestl . TimeOfBirth())

19
Chapter 1

, wait a while
For i = 1 To 500000000
Next

, call GetInstance() again


objTest2 = MySingleton.GetInstance()
Console.WriteLine("GetInstance() called at " &
Now.ToLongTimeString & ' ; " &
'objTest2 .TimeOfBirth()= ' &
objTest2.TimeOfBirth())

MessageBox .Show('Click OK to end")


End Sub

Of course, we can't use the New constructor to create them, because it sprivate. Ifyou try using code
like this:

Dim objTestl As New MySingleton()

... then you'll get an IntelliSense error message notification.

When you run this example, you should get output like this:

Creating Singleton at 16:43:51


GetInstance() called at 16:43:51; objTest1 . TimeOfBirth()=16:43:51
GetInstance() called at 16:43:57; objTest2.TimeOfBirth()=16:43:51

What does this show? First, there's only one Creating Singleton ... line, which shows that during the
course of this execution, the private New () constructor only runs once - so only one instance is created.
The subsequent lines show that the two object variables objTestl and objTest2 are references to the
same singleton object - the one that was created the first time Getlnstance () was called.

Singletons in Multithreaded Applications


There is one gotcha worth mentioning. When creating singletons for multithreaded applications, you
need to make sure they are thread-safe. In the example below, a Mutex object does the trick, but many
other techniques exist. That's the beauty of patterns - it's the idea that counts, not the code!

Public Class MySafeSingleton


• Private members
Private Shared m_Instance As MySafeSingleton
Private Shared mLTimeOfBirth As String
Private Shared m_Mutex As New System.Threading.Mutex()

, Private New constructor


Private Sub New()
Console.WriteLine("Creating Singleton at " & Now. ToLongTimeString)
m_TimeOfBirth = Now.ToLongTimeString
End Sub

• Public method for "creating" the instance


Public Shared Function GetInstance() As MySafeSingleton
m_Mutex.WaitOne()
If m_Instance Is Nothing Then
m_Instance = New MySafeSingleton()

20
Introduction to Design Patterns

End I f
~utex.ReleaseMutex()
Return mLlnstance
End Function

, Public property
Public ReadOnly Property TimeOfBirth() As String
Get
Return m_TimeOfBirth
End Get
End Property
End Class

The Abstract Factory Design Pattern

GoF Intent: Provide an interface for creating familie of related or dependent object
without specifying their concrete classe .

Suppose we have to write an interactive storybook application, which tells the story about a family of
three bears - Daddy Bear, Mommy Bear, and Baby Bear. Suppose also that the program must also be
able to tell this story using one of two bear families - either golden bears or brown bears. (Users ask for
the strangest things.) Of course, we will not know which family to use for the story until run time; some
users like to hear the story told with brown bears, others prefer to hear it told with golden bears.

Our application will need to create three objects in the implementation of this storybook application -
either GoldenDadBear, GoldenMomBear, GoldenBabyBear or BrownDadBear, BrownMomBear,
BrownBabyBear. What is the best, most flexible way for our code to instantiate all of the necessary
bear objects, based on the user's choice of "golden" or "brown"? This far-fetched design requirement
occurs more frequently than you might imagine, and matches the Abstract Factory design pattern.
A classic application ofAbstract Factory involves the creation ofentire families of GUJ widgets. Ifyou
ever build an application running on Windows and some future Linux-based shell, then you just might
need to manage the creation of toolbars, textboxes, dialog boxes, etc, based on the choice of operating
system. Here, as in our bear story application, the Abstract Factory pattern provides the solution.

A Simple Non-OO Solution


For the sake of comparison, before we examine the Abstract Factory solution let's take a look at a more
basic approach. We might consider begetting our bear family by using a simple decision structure. We'd
use a Select Case statement whenever we needed to decide which bear version of the desired family
member to create. We'd need a global variable (something like gBearFamily) that would remember
the user's preference for Golden or Brown bears. Then, when building an objBabyBear, we'd first
read the gBearFamily global variable; and based on its value we'd call the associated family's
BabyBear constructor within a Select Case:

Select Case gBearFamily


Case "Golden"
objBabyBear New GoldenBabyBear()
Case "Brown"
objBabyBear New BrownBabyBear()
End Select

21
Chapter 1

I am not going to rant about the evils and dangers of relying on global variables, because I have used
them too. Despite the honored membership of the global variable in the Spaghetti Code Club, the
fact is that VB6 developers were often hard-pressed to find a more efficient alternative.

Aside from the reliance on global variables, and the many Select Case statements now littering the
application, more significant problems could surface after the first release of the application. For
example, maybe we forgot that obj DadBear really came in three flavors, not two . And how easy is it to
keep those little changes in the BrownBabyBear class synchronized with its
GoldenBabyBear counterpart?

A More Flexible Design Pattern Solution


It is with such depressing prospects in sight that we bite the bullet and apply the Abstract Factory
pattern. After all, it was conceived for this exact situation - managing object creation given multiple
families of related objects.

Let's look at the UML for our solution, based on the Abstract Family pattern. It might be easier to
appreciate this pattern if you think of it in two parts - the "bear creation managers" and the "bear
implementers". In our storybook application, the three BearFactory classes (on the left) serve as the
object creation managers. The other classes implement the bears:

. ..
Bear Implementers

1 D';'" 1

r--:-- - .- ,
BearFactory I : I
+CreateDadBear() I : I
+CreateMomBear() I : I
I : I
+CreateBabyBear()
I : I
? I
I
I
:
:
I
I
I
I I I
GoldenBearFactory . I . I
____
+CreateDadBear() -------Ji'
~ _L_~ : ~

I -: 1
+CreateMomBear() : 1 : I
+CreateBabyBearO BrownBea rFactory . I : I

: &1';''' 1 ::
+CreateDadBear() :-T'- - - - - - - - - - - - - - - - - - - - - -"":-1
Bear Creation Managers +CreateMomBearO
+CreateBabyBearO
I : 1
I : 1
I : I
I . I
I I
I I

Let's see how this translates into code. We'll start by building the bear creation managers. First, here's
the BearFactory interface:

22
Introduction to Design Patterns

MustInherit Class BearFactory


Public MustOverride Function CreateDadBear() As DadBear
Public MustOverride Function CreateMomBear() As MomBear
Public MustOverride Function CreateBabyBear() As BabyBear
End Class

Next, we use this to build the two bear creation managers, GoldenBearFactory and
BrownBearFactory:

Public Class GoldenBearFactory : Inherits BearFactory


Public Overrides Function CreateDadBear() As DadBear
Return New GoldenDadBear()
End Function

Public Overrides Function CreateMomBear() As MomBear


Return New GoldenMomBear()
End Function

Public Overrides Function CreateBabyBear() As BabyBear


Return New GoldenBabyBear()
End Function
End Class

The colon (:) notation in the first line of this class is a line continuation character. The VB.NET
engine expects the Inheri ts BearFactory clause to be on a new line, like this:
Public Class GoldenBearFactory
Inherits BearFactory
I just prefer using the colon line continuation character - it makes the inheritance relation more obvious.

The BrownBearFactory creation manager is very similar to the GoldenBearFactory creation


manager we've just seen:

Public Class BrownBearFactory : Inherits BearFactory


Public Overrides Function CreateDadBear() As DadBear
Return New BrownDadBear()
End Function

Public Overrides Function CreateMomBear() As MomBear


Return New BrownMomBear()
End Function

Public Overrides Function CreateBabyBear() As BabyBear


Return New BrownBabyBear()
End Function
End Class

Now, we'll construct the bear implementers. We will use interfaces again, to ensure that all of our bear
family members act accordingly. For example, the interface BabyBear guarantees that
BrownBabyBear and GoldenBabyBear are good kids:

23
Chapter 1

Mustlnherit Class DadBear


End Class

Mustlnherit Class MomBear


End Class

MustInherit Class BabyBear


End Class

Having created the generic DadBear, MomBear, and BabyBear classes, we can describe the specific
Golden and Brown specializations that inherit from these classes. Here are the GoldenDadBear and
BrownDadBear classes that inherit from DadBear:

Public Class GoldenDadBear : Inherits DadBear


Public Sub New ( )
Console.WriteLine(TypeNarne(Me) .ToString & • Created')
End Sub
End Class

Public Class BrownDadBear : Inherits DadBear


Public Sub Ne~1 ( )
Console . WriteLine(TypeNarne(Me) . ToString & " Created")
End Sub
End Class

In order to keep the example simple, we've made these classes very small. We'll need four more classes
for GoldenMomBear, BrownMomBear, GoldenBabyBear, and BrownBabyBear:

Public Class GoldenMomBear : Inherits MomBear


Public Sub New ()
Console.writeLine (TypeNarne (Me) . ToString & ' Created')
End Sub
End Class

Public Class BrownMomBear : Inherits MomBear


Public Sub New()
Console.\~riteLine(TypeNarne(Me) . ToString & ' Created')
End Sub
End Class

Public Class GoldenBabyBear : Inherits BabyBear


Public Sub New ()
Console . WriteLine(TypeNarne(Me) .ToString & " Created")
End Sub
End Class

Public Class BrownBabyBear : Inherits BabyBear


Public Sub New()
Console.WriteLine(TypeNarne(Me) .ToString & • Created")
End Sub
End Class

24
Introduction to Design Patterns

It is worth noting how any Abstract Factory pattern rests on the strategic application of interfaces. It is
through interfaces that all of our "Bear Creation Managers" communicate with all of the "Bear
Implementation" classes.

Now we can write a little routine to test this. We'll use a simple message box to ask the user whether
they want to create a family of golden bears or a family of brown bears. The result is captured in the
object variable obj GoldenPreferred (which evaluates to either DialogResul t. Yes or
DialogResult .No):

Sub Main()
Dim objBearFactory As BearFactory
Dim objDadBear As DadBear
Dim objMomBear As MomBear
Dim objBabyBear As BabyBear
Dim objGoldenPreferred As DialogResult

, choose one of these


objGoldenPreferred = _
MessageBox . Show( _
"Click Yes for Golden Bears . Click No for Brown Bears", _
"Storybook Application", MessageBoxButtons . YesNo)

Then we use the value of objGoldenPreferred to create the appropriate BearFactory object:

, create a BearFactory, depending on user's selection


If objGoldenpreferred = DialogResult.Yes Then
objBearFactory New GoldenBearFactory()
Else
objBearFactory New BrownBearFactory()
End If

Finally, we can use the following generic code to create DadBear, MomBear, and BabyBear objects.
This code will use the BearFactory object selected above, and hence create members of the desired
bear family:

, use the BearFactory object to create DadBear, MomBear, BabyBear


objDadBear = objBearFactory . CreateDadBear
objMomBear = objBearFactory . CreateMomBear
objBabyBear = objBearFactory.CreateBabyBear

MessageBox.Show( "Click OK to end')


End Sub

The object constructors report to the console at the time they are executed, noting the object type being
created. So, when you run this application you should see a message box like this:

ckk Yes for Golden Bears, Click No for Brown Beers

Yes No

25
Chapter 1

If you click Yes, then the application will go ahead and tell the story using golden bears. You'll see this
output at the console:

GoldenDadBear Created
GoldenMomBear Created
GoldenBabyBear Created

If you click No, then the application will tell the story using brown bears, and you'll see this output at
the console instead:

BrownDadBear Created
BrownMomBear Created
BrownBabyBear Created

We had to create a foundation of 12 classes in order to be able to write such a generic piece of code in
the Main () routine. But with that foundation in place, the application as a whole is immensely scalable
and extensible. Abstract Factory not only manages existing families of objects, but also easily handles
the addition of new families.

However, there is one caveat. The constraining influence of the BearFactory class means that if you
create a new family, it must look very much like the existing families. If you wanted to add a new bear
family with teenagers, then things would get a little more complicated - it can't be done using the
Abstract Factory pattern alone. In fact, you might save the situation by using the Abstract Factory
pattern in conjunction with the Adapter pattern - but that discussion is for another time ...

The Factory Method Design Pattern

GoF Intent: Define an interface for creating an object, but let subclasses decide which
cla to instantiate. Factory Method let a cia defer instantiation to ubcla se .

Don't blink when watching Factory Method in action for the first time. If you do, you stand a good
chance of missing the subtlety of its magic. The underlying premise is rather simple. A common
requirement in applications is for an object factory class that creates an array of similar objects, like this:

Public Class InflexibleDwarfFactory


Private m_Dwarfs As New ArrayList()

Public Sub New ()


mLDwarfs.Add(New Dwarf('Bashful ' ))
m....Dwarfs . Add (New Dwarf ("Doc'))
mLDwarfs. Add (New Dwarf ("Dopey') )
m....Dwarfs.Add(New Dwarf ("Grumpy"))
m....Dwarfs.Add(New Dwarf("Happy"))
mLDwarfs.Add(New Dwarf('Sleepy'))
mLDwarfs.Add(New Dwarf("Sneezy'))
End Sub

Public Sub ShowDwarfs()

26
Introduction to Design Patterns

Dim aDwarf As Dwarf


Console.WriteLine("Created by • & TypeName(Me) .ToString & ":')
For Each aDwarf In m_Dwarfs
Console.WriteLine(aDwarf.Name)
Next
End Sub
End Class

This is a perfectly functional class, up to a point. However, what happens when we want to adapt this
object factory to create the Dwarf objects in a different order? Or when we want the object factory to
create a different set of Dwarf objects? Using the model above, we would be forced to revisit the
Dwarf Factory itself and re-code it.

We can achieve a much more flexible situation by applying Factory Method. Here, we replace the
default constructor, New ( ), with our own custom constructor method, AddDwarfs ( ) :

Public Class Dwarf Factory


Protected mLDwarfs As New ArrayList()

Public Overridable Sub AddDwarfs()


m_Dwarfs . Add (New Dwarf ("Bashful") )
m_Dwarfs. Add (New Dwarf ( "Doc" ) )
m_Dwarfs . Add (New Dwarf ("Dopey"»
m_Dwarfs . Add (New Dwarf ("Grumpy") )
m_Dwar f s . Add (New Dwar f ( "Happy" ) )
m_Dwarfs . Add(New Dwarf ("Sleepy") )
m_Dwarfs . Add (New Dwarf ("Sneezy") )
End Sub

Public Sub ShowDwarfs()


Dim aDwarf As Dwarf
Console. WriteLine ("Created by " & TypeName (Me) . ToString & ":")
For Each aDwarf In m_Dwarfs
Console.WriteLine(aDwarf.Name)
Next
End Sub
End Class

Now, the array of Dwarf objects is Protected, rather than Private - thus, any object that inherits
from Dwarf Factory has access to the array. Just as significantly, the AddDwarfs () constructor
method is Overridable, which means that an inheriting object can implement its own AddDwarfs ()
constructor method.

It is not possible to make New () overridable, and this is another reason why the
InflexibleDwarfFactory class really is so infleXible.

So let's use our Dwarf Factory class to build an application to illustrate its newfound flexibility. We
haven't created the Dwarf class yet, so let's do that next. This simple class contains an implementation
of the default constructor, New ( ) , which sets the dwarfs name. It also has a read-only Name property.
All of our fairy tales will need this little helper class:

27
Chapter 1

Public Class Dwarf


Private RLName As String

Public Sub New(ByVal Name As String)


RLName = Name & " the " & TypeName (Me) . ToS t ring
End Sub

Public ReadOnly Property Name() As String


Get
Return m_Name
End Get
End Property
End Class

We'll write a little application that tells two stories: first, it tells the story of Snow White (which, as we all
know, features seven dwarfs). Then, it will tell a new story, Snow White II The Sequel, in which Dopey
travels to visit his Scottish cousins Morag and Murdo. For the second story, we'll create a new object
factory based on Dwarf Factory, like this:

Public Class SnowWhiteIIDwarfFactory Inherits Dwarf Factory


Public Overrides Sub AddDwarfs()
RLDwarfs . Add (New Dwarf ("Dopey'»
RLDwarfs . Add (New Dwarf ("Cousin Morag"»
m_Dwarfs. Add (New Dwarf ('Cousin Murdo"»
End Sub
End Class

ow we can tell the two stories:

Sub Main()
Dim obj SnowWhiteO\>/arfFactory As New Dwarf Factory ()
objSnowWhiteDwarfFactory.AddDwarfs()
objSnowWhiteDwarfFactory . ShowDwarfs()

Dim objSnowWhiteIIDwarfFactory As New SnowWhiteIIDwarfFactory()


objSnowWhiteIIDwarfFactory.AddDwarfs()
objSnowWhiteIIDwarfFactory.ShowDwarfs()

MessageBox.Show("Click OK to end')
End Sub

When you run the application, you should see the following output. Admittedly, the plot of these two
stories is not strong, but you can see that the character list is different:

Created by Dwarf Factory:


Bashful the Dwarf
Doc the Dwarf
Dopey the Dwarf
Grumpy the Dwarf
Happy the Dwarf
Sleepy the Dwarf
Sneezy the Dwarf

28
Introduction to Design Patterns

Created by SnowWhiteIIDwarfFactory:
Dopey the Dwarf
Cousin Morag the Dwarf
Cousin Murdo the Dwarf

Thus, although we have added a little complexity in the way the Dwarf objects are created (inserting an
extra constructor method in addition to the existing constructor), we have gained flexibility by
encapsulating object creation without encumbering the default constructor. In fact, this feature is
invaluable in situations when the superclass's default constructor is more complex than that of the
Dwarf Factory constructor. For example, what if the Dwarf Factory constructor included a user
authentication mechnaism? Would you (or could you) include that logic in your new constructor?

Some programmers consider Factory Method to be a default coding style. Indeed, many developers feel
that the ability to take explicit control of object creation is so important that it should never be left
sitting in the middle of some arbitrary method. The power and flexibility gained by taking control via
Factory Method (and indeed Abstract Factory) are quite significant, as we've seen here.

At this point, we will leave the subject of creational patterns, and move on to look at some structural patterns.

Structural Patterns
Structural patterns govern how objects and classes work together. The most common feature of these
patterns is that they all work by inheritance. Each pattern applies the principles of inheritance in quite
different ways to accomplish its ends. Some patterns, like Adapter, apply inheritance with incredible
simplicity, while others require a little coffee and serious thought.

Before we go crazy with inheritance, it s worth noting a warning expressed by the GoP in relation
to the question of object inheritance versus object composition. In brief, they expressed a strong
preference for composition when faced with a choice between it and inheritance. Ifyou ever built an
application relying on a superciass that someone changed without your knowledge, then you
probably have an idea why they said that!

The GoF cataloged seven structural patterns: Adapter, Bridge, Composite, Decorator, Fa~ade,
Flyweight, and Proxy. We'll cover all but Flyweight here.

The Adapter and Fa~ade Design Patterns

GoF Intent for Adapter: Convert the interface of a class into another interface clients
expect. Adapter lets cla e work together that couldn't otherwise because of incompatible
interfaces.

GoF Intent for Fa~ade: Provide a unified interface to a et of interface in a ub y tern.


Fa~ade defines a higher-level interface that makes the subsystem ea ier to u e.

The purpose of the Adapter pattern is not ambitious. It is designed simply to adapt the interface of a
class so that it is compatible with the client that needs to use it. This requirement may be as trivial as
changing method names to fit your application's conventions.

29
Chapter 1

By contrast, the Fat;ade (pronounced "fa-sahd') pattern does a little more work. It creates a "fa~ade
class", which acts as a layer between the client and a set of service classes. The client then sends its
requests to an instance of the fa~ade class, which acts as an agent - manipulating the requests as
necessary and sending them on to the set of service classes. The purpose of the fa~ade class is to
eliminate the difficulties that the client would otherwise have in sending requests to a complex set of
service objects.

From these initial descriptions, it's rather difficult to tell these two patterns apart. Indeed, in practice
they can often be used interchangeably, because both patterns deal with the task of changing classes'
interfaces in order to make them easier for the client application to use.

However, as we'll see in the examples that follow, the structure of these two patterns is different, and
they do solve two subtly different problems. In particular, we'll include a UML diagram that describes
how the following two applications implement the two patterns - the difference between Adapter and
Fa~ade becomes clearer when you compare these two diagrams.

The Adapter Pattern - an Example


Suppose we are designing a restaurant ordering system. It will make use of two classes:

o A class that handles orders for a fast food restaurant. This class will be called
FastFoodOrderer, and we'll write it in-house.
o A class that handles orders for a fancy French restaurant.

However, at the time of the first release, the second of these classes will not be available to us. In fact,
this class is to be coded by a third party and we don't even know its interface yet. Therefore, the first
release of the application will only allow the user to order food from a certain no-frills fast food
restaurant. For the second release, we want to be able to adapt the third party class and insert it
seamlessly into the existing application.

In order to do this, the client application will have a single object called obj FoodOrderer, which is
capable of ordering both fast food and French food. Food will be ordered through the method
objFoodOrderer . Order (). Our FastFoodOrderer class will also have an Order () method. We
don't know whether the French restaurant class will have an Order () method, but it doesn't matter.
We'll design the application in such a way that we'll be able to adapt its interface to fit our application.

Here is the UML diagram for our application. It includes the implementation of the third-party class,
which (as it turns out) is called FrenchRestaurant, and has a method called OrderFromMenu ():

« interface»
FoodOrderer I FrenchRestaurant I
. . - The Adaptee
+Order() I +OrderFromMenuO I

I
\/-,
,,
,, ,,
,
----, ,
,
: ,

LFastFoodOrderer I F
I renchFoodOrdererl
. - The Adapter
I +OrderO I I +OrderO J

30
Introduction to Design Patterns

This pattern allows us to use polymorphism in our client application to create an instance of a
FoodOrderer class, and use its Order () method. What happens next depends on what the user has
asked for:

o If the user is ordering French food, the application will use the implementation of Order ( )
provided by the FastFoodOrderer class.
o If the user is ordering fast food, the application will use the implementation of Order ( )
provided by the FrenchFoodOrderer class. This class is the adapter class - it adapts the
OrderFromMenu () method of the FrenchRestaurant class (the adaptee), allowing the
client application to use it indirectly.

Without this adapter/adaptee pattern, recoding our second release would be rather more difficult. In
order to facilitate calls to FrenchRestaurant, it might be possible to convert FoodOrderer to an
abstract class, perhaps add some new, specialized methods tcFrenchRestaurant. Either way, these
are rather less than desirable options.

Let's see how our application develops. First, here's the FoodOrderer interface:

Public Interface FoodOrderer


Sub Order(ByVal Request)
End Interface

Now, here's the FastFoodOrderer class that implements the FoodOrderer interface:

Public Class FastFoodOrderer : Implements FoodOrderer


Public Sub Order(ByVal Request) Implements FoodOrderer.Order
Console.WriteLine(Request & II coming up. ")
End Sub
End Class

And here's the first version of the client application. It includes some simple test code in which we use
the FoodOrderer object to order some fast food:

Sub Main ()
Dim objFoodOrderer As FoodOrderer

Console .WriteLine("Let's order from the Fast Food restaurant: ")


objFoodOrderer = New FastFoodOrderer()
objFoodOrderer.Order("l Cheeseburger")

MessageBox.Show("Click OK to end")
End Sub

When you run this, you can see (in the console output) that the FastFoodOrderer object has handled
the request for a cheeseburger:

Let's order from the Fast Food restaurant:


1 Cheeseburger coming up.

After this first release, the third party delivers its implementation of the French restaurant class. This is
what they deliver:

31
Chapter 1

Public Class FrenchRestaurant


Public Sub OrderFromMenu(ByVal Request)
Console.WriteLine(Request & "? Oui, monsieur . Bon appetit . ")
End Sub
End Class

The rules of polymorphism won't allow the obj FoodOrderer object to be instantiated to type
FrenchRestaurant, because they're not related. So, we now build our FrenchFoodOrderer class:

Public Class FrenchFoodOrderer : Inherits FrenchRestaurant


: Implements FoodOrderer
Public Sub Order(ByVal Request) Implements FoodOrderer.Order
OrderFromMenu(Request)
End Sub
End Class

The first line of the adapter class of the application, FrenchFoodOrderer, is quite busy - it inherits
and implements simultaneously. This is not an unusual 00 construction. It appears quite often within
the .NET Common Language Runtime (CLR) itself.

Now we can add some extra code to the client application, to demonstrate that objFoodOrderer is
indeed capable of ordering food from either establishment:

Sub Main()
Dim objFoodOrderer As FoodOrderer

Console.WriteLine("Let's order from the Fast Food restaurant: ")


objFoodOrderer = New FastFoodOrderer()
objFoodOrderer . Order("l Cheeseburger")

Console .WriteLine("Now let's order some French food" &


"from their fancy restaurant menu: ")
objFoodOrderer = New FrenchFoodOrderer()
objFoodOrderer.Order("Moules Mariniere")

MessageBox.Show("Click OK to end")
End Sub

Here's the output:

Let's order from the Fast Food restaurant :


1 Cheeseburger coming up.
Now let's order some French food from their fancy restaurant menu:
Moules Mariniere? Oui, monsieur . Bon appetit.

While we've tried to avoid unnecessary code here, the main structure ofthe pattern is clear. We can
now use a similar technique to add more classes, which communicate orders to other restaurants. In
each case, we'd simply add the third-party object and an adapter object. In our application, the
obj FoodOrderer object would be able to assume the role of any of the adapter objects, and pass food
orders to any eaterie in town!

32
Introduction to Design Patterns

The Fat;ade Pattern - an Example


To demonstrate the Far;ade pattern, we'll continue on the theme of food, this time but present a different
problem. This is another application that orders food - but this time, the order involves a number of
calls to the methods of three service classes (SupermarketVisi t, Cleaner, and MealPreparer).
Overall, we think that the complexity of these method calls is too much. Our developers can certainly
all figure out how to make all these calls, but why should they all waste time learning a complex API?
This is where the Far;ade design pattern comes in.

To solve this problem, we create a new class or interface that manages all the calls to the methods of the
three service classes. At the cost of one class, we will make it very easy for any developer to order some
food without navigating a bunch of some potentially complex interfaces!

... ........ ....... . ... .


SupermarketVlslt
.....
Cleaner
,...----,
MealPreparer
,

The "Old" Interfaces


f-----J
+BuyFoodO +ClearTableO +CookFoodO

..",.. .... ...... .


+WashDishesO ,
.... . ..:. .... .. ............ ... .
t__ _. . ___________ ________________ _____1
• • • • • • •.
• I • •

_~ ~

Host
~ The "New ' interface
1-------;
+Ente rtai nGuestsO

Let's start at the top of our UML diagram with the three service classes. For the sake of brevity, we'll use
three simple service classes. You'll need to pretend that they have horribly complex interfaces:

Public Class SupermarketVisit


Public Function BuyFood(ByVal Food As String)
Console .WriteLine("Buying some" & Food & " .. . ")
Return Food
End Function
End Class

Public Cl ass MealPreparer


Public Function CookFood(ByVal Food As String)
Console.WriteLineC'Cooking the' & Food & " ... oJ
Return Food
End Function
End Class

Public Class Cleaner


Public Sub ClearTable()
Console. Wri teLine ( "Clearing t he Table . .... )
End Sub

Public Sub WashDishes()


Console . WriteLine("Washing the Dishes . .. 0)
End Sub
End Class

33
Chapter 1

Now we'll write our fac;:ade class, which acts as an agent - making the use of these service objects very
easy for the client application:

Public Class Host


Public Function EntertainGuests(ByVal Entree As String)
Dim objSupermarketVisit As New SupermarketVisit()
Dim objMealPreparer As New MealPreparer()
Dim objCleaner As New Cleaner()

objMealPreparer.CookFood(objSupermarketVisit.BuyFood(Entreel)
objCleaner.ClearTable()
objCleaner.WashDishes()

Console.WriteLine('What a pleasant evening. ')


End Function
End Class

As you can see, the Host class performs all the necessary roles in one simple function call: buying the food,
preparing it and cleaning up afterwards. The interface for the Host class is much simpler than the combined
API of the three service objects, and this makes the code in the client application extremely simple:

Sub Main()
Dim objHost As New Host()
objHost.EntertainGuests("Pasta")

MessageBox.Show("Click OK to end')
End Sub

This is what you will see in the console window when you run this application:

Buying some Pasta .. .


Cooking the Pasta .. .
Clearing the Table .. .
Washing the Dishes .. .
What a pleasant evening.

Notice how all we had to do was call EntertainGuests () and the rest was all done for us. Much easier
than having to put in all those different calls every time our program wanted to throw a dinner party!

Comparing the Adapter and Fa(:ade Patterns


Finally, note that an Adapter pattern would not have helped us much here. The problem is not that we
cannot call the SupermarketVisi t, Cleaner, and MealPreparer interfaces as they exist. Rather, it
is that having to use them at all is a pain! It is this observation that really highlights the difference
between the Adapter and Fac;:ade patterns.

The BrIdge DesIgn Pattern

GoF Intent: Decouple an abstraction from its implementation 0 that the two can vary
independently.

34
Random documents with unrelated
content Scribd suggests to you:
Garuda to proceed (10). O king, before Nikumbha, unconquerable in
battle, could reach the city of Vajra, Pārtha and Krishna, the slayers
of their enemies, overtook him in the way (11). Beholding them the
highly powerful Pradyumna, the foremost of those conversant with
illusions, divided himself into three portions (12). On the other hand,
Nikumbha, like unto an immortal, smilingly fought with them all with
heavy clubs (13). Holding the maiden Bhānumati by his left hand,
the great Asura Nikumbha repeatedly hurled the club with his right
hand. Although thus assailed, Keshava, Kāma (Pradyumna) and
Arjuna, none, could strike him ruthlessly lest they might wound the
maiden (14-15). O king, although capable of slaying that
irrepressible enemy they began to sigh piteously out of their
excessive compassion for the maiden (16). As when a serpent gets
round a camel, a man, well up in the use of arms, strikes the
serpent leaving the camel to itself, so Pārtha, the foremost of
archers, began to strike the Daitya with his arrows (17). In
pursuance of the rules of art, their training and reasoning, Pārtha,
Kāma and Krishna did not strike the maiden but wounded the
Danavas with their cane-like arrows (18). Thereupon resorting to his
illusory powers Nikumbha so disappeared with the maiden from that
place that nobody could know it: Krishna, Kāma and Dhananjaya
however immediately pursued him: he, however, went on assuming
the semblance of a yellow vulture (19-20). Thereupon saving the
maiden, the heroic Dhananjaya assailed him again with cane-like
arrows piercing his very vitals (21). Thus pursued by those heroes
that great Asura, the slayer of his enemies, travelled all over the
earth consisting of seven insular continents and dropped down with
the maiden at last on the bank of the river Chela Gangā flowing on
the summit of the mount Gokarna (22–23). None amongst the gods,
Asuras or great ascetics could cross that mountain protected by the
energy of Mahadeva (24). Finding this weak point of Nikumbha, the
Bhaima chief Pradyumna, invincible in battle and quick coursing, got
hold of the maiden Bhānumati. And Krishna, and Arjuna began to
assail the Asura greatly with arrows. Then leaving the northern
range of the mount Gokarna, Nikumbha fled to the southern range.
Both the Krishnas however, riding on Garuda, pursued him (25–26).
Gradually the great Asura entered into Shatpura, the abode of his
kinsmen and those two heroes spent the night at the mouth of the
cave. With Krishna's permission the heroic son of Rukshmini
delightedly took Bhaima's daughter to the city of Dwārakā. And
keeping her there he returned to Shatpura, full of Dānavas and
beheld the two Krishnas of dreadful prowess at the mouth of the
cave (27-29). Thus occupying the entrance of the city of Shatpura
the highly powerful Krishna and Arjuna, desirous of slaying
Nikumbha, waited there with Pradyumna (30).
Thereupon desirous of fighting the highly powerful Nikumbha
came out of the cave, O king, no sooner he came out of the cave
than Dhananjaya, with arrows shot off his Gandiva bow, obstructed
the thorough-fair. In spite of it Nikumbha, the foremost of the
powerful, came out, took up his club covered with thorns and struck
Pārtha on his head (31–33). Thus assailed with that club Pritha's son
vomitted blood and lost his consciousness. The Asura, master of
illusions, smilingly struck the heroic son of Rukshmini, the foremost
of those conversant with illusions, who was waiting with his face
against him. Wounded on the head with that unseen stroke of the
club the heroic Pradyumna lost his consciousness. Beholding them
thus assailed and insensible Govinda, having Gada as his elder
brother, beside himself with anger, took up his club Koumodaki and
ran towards Nikumbha. Those two irrepressible heroes, roaring,
fought with each other (34–37). Riding his elephant Airāvata along
with the gods Sachi's Lord began to witness that dreadful combat
like unto the battle between the celestials and Asuras. Beholding the
gods Hrishikesha, the slayer of his enemies, tried to kill the Dānavas
in a wonderful battle, desirous of doing good unto the gods (38-39).
Whirling his Koumodaki, the large-armed Keshava, conversant with
military science, displayed many wondrous manoeuvres (40).
Nikumbha too, the foremost of Asuras, by virtue of his training
hurled his club, covered with many thorns, and displayed various
manoeuvres (41). At that time they fought like two roaring bulls for
a cow, two roaring elephants and two leopards worked up with
anger (42). O Bhārata, thereupon setting a highly dreadful shout,
he, with his club, set with eight bells, struck Krishna having Gada as
his elder brother. He too hurling his huge club threw it on
Nikumbha's head (43-44). At that time holding idle for a moment his
Koumodaki club the intelligent preceptor of the world, Hari fell down
insensible on earth (45). O king, while the high-souled Vasudeva was
reduced to this plight the whole world was filled with lamentations.
With the cool water of Mandākini mixed with ambrosia, the king of
gods himself sprinkled Keshava. O king, Krishna, the foremost of
gods, did so of his own accord, or else who can render the high-
souled Hari insensible?
O descendant of Bharata, thereupon regaining his
consciousness, Krishna, the slayer of his enemies, took up his discus
and asked the wicked Asura to bear it (49). At that time casting off
his body there the irrepressible Nikumbha, a great Māyāvin, went
away. Keshava however could not know it (50). Thinking that either
he was dead or on the point of death and remembering the
obligations of the heroes he did not strike him who was fallen.
Thereupon regaining their consciousness Pradyumna and Arjuna
came there and considering Nikumbha dead stood by Krishna (51-
52). Afterwards coming to know of the real truth Pradyumna,
conversant with illusions, said to Krishna:—"O father, the wicked
Nikumbha is not here. He has fled somewhere else" (53). No sooner
Pradyumna said this than Nikumbha's body disappeared. Seeing it
the powerful Lord, with Arjuna, laughed (54). O heroic king, few
minutes after they saw all over the earth and welkin thousands of
Nikumbha. The spectators also saw the heroic Krishna, Pārtha and
Rukshmini’s son in innumerable forms. It appeared indeed wonderful
(55–56). At that time amongst those great Asuras some held
Pārtha's bow, some his huge arrows, some his hands and some his
feet (57). Thus when the innumerable bodies of Pārtha were caught
the Asuras carried away the heroic Dhananjaya to the sky. Thus
when separated from Pārtha the heroic Krishna and his son pierced
Nikumbha with numerous shafts. Still they could not see his end.
One Nikumbha, divided into twain, became two. Thereupon seeing
every thing correctly by his celestial wisdom the Divine Lord Krishna,
the origin of the present and future and the slayer of Asuras, saw
the true form of Nikumbha, the creator of illusions and the stealer of
Dhananjaya. And before the presence of all creatures he, with his
discus, cut off his head (58–62.) O descendant of Bharata, when his
head was thus sundered that foremost of Asuras, leaving aside
Dhananjaya, fell down like an uprooted tree (63). O giver of honors,
at that time Pārtha was about to drop down from the sky. At
Krishna's mandate his son held him up (64). When Nikumbha thus
fell down on earth the deity Krishna consoled Keshava and with him
repaired to Dwarakā (65).
Having returned delightedly to Dwarakā the Lord Krishna, O
descendant of Yadu, and the foremost of Dāsharhas, saluted the
high-souled Narada (66). Thereupon the highly energetic Nārada
said to Bhānu:—"O descendant of Bhaima, do not consider yourself
insulted on account of your daughter being carried away (by
another). O Bhānu, listen to great cause hereof (67). O hero, on one
occasion while sporting in the garden of Raivata, this your daughter
excited the anger of the foremost of Munis Durvāsā who wrath fully
imprecated a curse on her saying:—'She is very much ill-mannered
and she must fall into the hands of an enemy.' At that time, myself
along with other Munis, propitiated him on behalf of your daughter
saying:—'Muni, O foremost of the pious, dost thou, informed of the
essence of religion as thou art, imprecate a curse on this innocent
girl who is observing her religious obligations? We request thee to
show favour into her' (68-70). O Bhaima chief, after we had said this
Durvāsā stood with his face down for a moment and then stricken
with compassion said:—'What I have said will prove true. It will
never be otherwise. Forsooth she will fall into the hands of an
enemy. Although thus fallen into the hands of an enemy she will not
be virtually contaminated; and she will obtain a beautiful husband,
will be lucky, a mother of many sons and mistress of immense
riches; this thin-built lady will always have beautiful fragrance
around her person, will always remain youthful and will forget the
sorrow consequent upon her being carried away by the enemy (71–
74)'. O hero, thus it had been pre-ordained so for Bhanumati before;
do you now confer her on Sahadeva for that son of Pandu is
virtuous, respectful and heroic (75)".
Thereupon regarding the words of Nārada, the virtuous souled
Bhāima gave away Bhāuumati to Madri's son Sahadeva (76). Having
sent an emissary Keshava, the holder of discus, had brought
Sahadeva there. After the wedding ceremony was over, he, with his
wife, returned to his own city. The man, who reverentially listens to
this conquest of Krishna or reads it, acquires success in every
business (77-78).
CHAPTER CCXXXVIII. THE DESTRUCTION OF
VAJRANABHA: AN ACCOUNT OF PRABHAVATI.

Janamejaya said:—O Muni, O thou the foremost of the pious, I have


listened to an account of the stealing away of Bhānumati, the
conquest of Keshava, the bringing of Chlālikya from the celestial
region, and the god-like sport of the Vrishnis of incomparable energy
in the ocean and many other wonderful subjects. While describing
the destruction of Nikumbha you have mentioned that of
Vajranābha. O Muni, I am now curious to hear this (1–3).
Vaishampāyana said:—O great king, O descendant of Bharata,
hear, I shall now describe the destruction of Vajra nābha with an
account of the victories of Kāma and Shāmva (4), O victor of armies,
a great Asura, celebrated by the name of Vajranābha, practised hard
austerities on the summit of the mount Sumeru. Pleased with his
penances the Divine Brahmā, the grand-father of the world, asked
him to pray for a boon (5–6). O king Janamejaya, thereat, that
foremost of Dānavas prayed for two boons that even the gods might
not kill him, and that he might get the city Vajra where even the air
cannot easily enter, which gives every sort of desired-for objects
even when they are not thought of, which has gardens encircled by
walls, many branch cities, and peerless jems of every description (7–
9). By that boon he got what he wanted and the great Asura
Vajranābha lived in the city of Vajra (10). O king, seeking refuge
with that great Asura who had obtained this boon, millions of
demons lived in that city of Vajra, in his garden and in many
charming branch cities. O king, the enemies of the gods lived there,
healthy, well-fed and contented (11-12). Once on a time, elated with
the pride of the boon given in his favour and that of his city the
wicked Vajranābha got himself ready to impede the course of the
world. O king, approaching the king of gods he said "O slayer of
Pāka, all the three worlds are the common properties of all the high-
souled sons of Kashyapa. I therefore wish to govern the three
worlds. If you, O king of gods, do not approve of my proposal, give
me battle" (13-15).
O descendant of Kuru, hearing the words of Vajranābha,
Mahendra, the foremost of celestials, consulted with Vrihaspati and
said:—"O gentle one, our father, the ascetic Kashyapa, is now
engaged in a sacrifice. After its termination he will do what is fair"
(16–17).
Thereupon the Dānava went to his father Kashyapa and
expressed his desire. Kashyapa said what the king of gods had
communicated (18). "O son, go now to the city of Vajra and live
there controlling yourself. After the termination of the Yajna I will do
what is fair" (19). Thus addressed Vajranābha returned to his own
city.
Thereupon Mahendra went to the city of Dwāravati having many
doors and communicated secretly to Vāsudeva what Vajranābha had
said. Thereat Janārddana said "O Vāsava, the horse-sacrifice of
Vasudeva is now at hand. After its termination I will kill Vajranabha
(20–22). O lord, O refuge of the pious, even the wind cannot enter
into his city if Vajranābha does not wish it. At a convenient hour we
will concert measures for entering there" (23).
O descendant of Bharata, honored by Vāsudeva's son in his
horse-sacrifice the king of gods set out (24). Even before the
termination of Vasudeva's sacrifice the heroic Vāsava and Keshava,
the foremost of celestials, began to think of means for entering into
the city of Vajra (25).
During the celebration of Vasudeva's sacrifice an actor, by name
Bhadra, pleased the great saints with his beautiful acting. The
leading Munis then asked him to pray for a boon. Thereupon saluting
those best of Munis assembled in the horse-sacrifice, the actor
Bhadra, resembling the king of gods himself, as desired by Krishna
and as if urged on by the goddess of learning, prayed for the
following boon (26-28).
The actor said:—"O foremost of Munis, may I become the food
of all the twice-born ones: may I range over the earth consisting of
seven insular continents: may I, without any obstruction, range all
over the sky: may I be gifted with strength and be not slain by all
creatures mobile and immobile. May I assume any form I like either
of one born, dead or immediately born. May not decrepitude
overtake me and may the Munis always remain pleased with me"
(29–32).
O king, the Munis said "So be it." That immortal-like one began
to range all over the earth consisting of seven insular continents. He
began to show his performances in the cities of the Dānava kings, in
Uttarakura, Bhadrāshwa, Ketumāl and the island of Kalāmra. On the
occasion of every Parva, that great actor, who had obtained the
boon, used to come to Dwarakā adorned with the Yadavas (33–35).
Thereupon, one day, the Divine Sakra, the king of gods, said to
Dhārtarāshtra swans:–"O celestial birds, although you are the
carriers of the gods and the pious, still you are our brothers on
account of your being begotten by Kashyapa (36–37). Now the great
duty of killing the enemies of the gods awaits us. You should satisfy
it. But take care, don't divulge the counsel (38). If you do not obey
the commands of the gods you will meet with a hard punishment. O
foremost of swans, you can go anywhere you like (39). Therefore
going to the most excellent city of Vajranabha where no one else
can enter you should range in the tanks of his inner appartment
(40). Vajranābha has a jewel of a daughter, peerless in beauty, in
the three worlds, by name Prabhāvati who is fair like the rays of the
moon (41). I have heard that her mother has obtained that beautiful
daughter by virtue of the boon conferred by the goddess Haimavati
(42). O Swans, her friends have kept that beautiful and chaste
maiden for Swayemvara and she too will select a husband of her
own accord. Do you describe to her the various accomplishments,
family, beauty, character, and age, of the high-souled Pradyumna
(43-44). When you will find that the chaste daughter of Vajranābha
has felt some attachment for Pradyumna, take carefully her news to
Pradyumna and return with his message to her. In this work of an
emissary you should, according to your intelligence, govern your
eyes and faces. You should thus do me a good turn now (45–47). O
swans, what more shall I speak, you should describe all these
accomplishments of Pradyumna to her, which will likely attract
Prabhāvati's mind; you should communicate to me and to my
younger brother Krishna at Dwāravati daily what happens there (48–
49). You should thus exert yourselves so long as the self-controlled
Lord Pradyumna does not carry away Vajranābha's daughter (50).
Those Dānavas, elated with the pride of the boon conferred by
Brahmā, are not to be slain by the gods. So their destruction in the
battle-field should be brought about by Pradyumna and other sons
of gods (51). An actor, Bhadra by name, has of late obtained the
boon (of entering into his city). So the Yadavas, headed by
Pradyumna, will enter into Vajranābha's city in his guise (52). O
Dhārtarāshtras, you are to do all that I have said. Besides for doing
me this good you should do what more crops up in time. O swans,
to enter into the city of Vajra depends on his will. The gods cannot
enter there by any means whatsoever (53–54)".
CHAPTER CCXXXIX. THE CELESTIAL SWANS
GO TO THE CITY OF VAJRA

Vaishampāyana said:—O king, from before the swans used to go to


the city of Vajra. So hearing the words of Vāsava they at once went
there (1). O hero, those birds jumped into the charming tanks filled
with golden lotuses and lilies which could be touched. Although they
had come many a time before they now astonished all with their
polished and sweet words (2-3). O king Janamejaya, speaking in
sweet words those celestial swans ranged in the tanks of
Vajranābha's inner appartment and became his great favorites. He
then said to those Dhārtarāstras the following words (4-5). "You
speak these sweet words because you always live in the celestial
region. Come here always whenever you will know of a great festival
in my house. O swans living in the celestial region, regard this house
of mine as your own and enter here confidently" (6–7). O
descendant of Bharata, thus addressed by Vajranābha those birds
entered into the palace of the king of Dānavas: for the work of the
gods they spoke like men and made acquaintance with all speaking
various words (8–9). At that time the women, who were living in the
palaces of Kashya pa's sons (Dānavas) partakers of all forms of
blessings, attained to great delight on hearing of that beautiful
account of the swans (10).
Thus ranging in the inner appartment of Vajranābha, the swans
saw his beautiful and smiling daughter Prabhāvati and made her
acquaintance (11). Amongst them the goose Shuchimukhi
contracted friendship with the princess of charming smiles (12).
Relating hundreds of beautiful stories Shuchimukhi created the
confidence of Vajranābha's daughter and one day she said to her
(13). "O Prabhāvati, I consider you the most beautiful in the three
worlds as regards your beauty, character and accomplishments. I
wish to tell you some thing (14). O you of beautiful smiles, your
youth is almost gone: that which is gone does not return like the
water of a stream (15). There is no other happiness to women
greater than enjoyment with men in this world. I tell you the truth,
O auspicious lady (16). O you of fair limbs, although ordered by your
father to make a free choice, why do you not select one of the gods
or Asuras as your husband? (17) O youthful lady, many a
bridegroom, endued with beauty, heroism and other
accomplishments, come here and go away disregarded. O lady,
when you do not like a bridegroom becoming your family and
beauty, why should then, O you of fair limbs, Rukshmini's son
Pradyumna, who has none in the three worlds equal to him, in
bravery, accomplishments, pedigree and beauty, come here (18-20)?
O you of a beautiful waist, although he is a man of men, that highly
powerful and virtuous-souled one shines like a god amongst the
gods and like one of them amongst the Dānavas (21). Seeing him
the women cannot cheque their natural love as the cow cannot
cheque its milk and the stream its water (22). I dare not compare
his face with the full-moon, his eyes with lotuses and his gait with
that of a lion (23). O fair lady, what more shall I say? The powerful
Lord Vishnu, having brought Cupid (the limbless god, Ananga) under
his subjection as one of his limbs, has created him as his son,
extracting the very essence of the world (24). He was stolen away,
in his childhood, by the sinful demon Shamvara: having slain him
and kept his character unscathed he learnt all his illusory powers
(25). All the accomplishments, that are worthy of being sought for in
the three worlds, and all those that you can imagine, exist in
Pradyumna. In his effulgence he is like fire, in patience he is like
earth, in lustre he is like a lake." Hearing it Prabhāvati said to
Suchimukhi (26–27):
"O gentle lady, I have heard many a time from the conversation
between my father and the intelligent Nārada that Vishnu is living in
the land of men (28). With burning cars, Shrānga (bow) and club he
has consumed the races of the Daityas. O honourable lady, he is the
great enemy of the sons of Diti and should be shunned by them.
The king of Danavas collects information about Vishnu from the
Asuras who live in the branch cities for his well-being. O you of
sweet smiles, every woman wishes that the family of her husband
may be superior to that of her father. If you however can find out
any means for bringing him here you will show me a great favour
and purify our family. I ask you, O you of sweet words, tell me how
Pradyumna, born in the family of Vrishnis, may become my husband.
I have learnt from the conversation of elderly Asura women that Hari
is a great enemy of the Daityas and gives them great trouble. I had
heard before how Pradyumna was born and how the powerful
Shamvara was killed by him. What more shall I say? Pradyumna is
always present in my heart. But the means by which I may be united
with him is solely wanted. O friend, learned you are no doubt; still as
a maid servant of yours, I appoint you as my emissary. Point out to
me the means by which I may be united with him." Thereupon
consoling her Suchimukhi smilingly said:—(29–38).
"O you of sweet smiles, I will go there as your emissary and
communicate to him your great devotion (39). O you of beautiful
waist, O you of sweet smiles, I will so exert that he may come here
and you may become the consort of Cupid (40). O you of fair eyes,
regard what I have said as true. Communicate to your father that I
speak cleverly; you will reap a great benefit therefrom".
Thus spoken to by the goose Prabhāvati acted accordingly. The
king of Dānavas said to the goose in his inner apartment. "O
beautiful Suchimukhi, Prabhāvati has communicated to me about
your cleverness in speaking. Do you describe to us becoming stories.
Tell us what wonders you have seen in this world, not seen before
by any and whether worthy or unworthy of being seen by others." O
king, the goose then said to Vajranābha (41–45).
"O foremost of Dānavas, I have seen an intelligent saintly lady,
by name Shāndili, perform a wonderful feat by the side of the mount
Sumeru (46). That Shandili, the good friend of the auspicious
daughter of the mountain chief (Uma) is large-minded and a great
benefactress of the world (47). I have also seen the auspicious actor,
who has obtained a boon from the Munis, who can assume shapes
at his will, who always gives food to all in the three worlds and is
liked by all. O sinless hero, that actor travels always in Uttarakuru,
the island of Kalamra, Bhadrāshwa, Ketumal, and other islands. He
knows many songs and dances of the gods and Gandharvas. And
with his dancing he surprises the gods (48–50)."
Vajranabha said:—"O goose, I had heard of this many a time
before. The high-souled Siddhas and Chāranas had mentioned this
to me (51). O daughter of a bird, I am also stricken with curiosity for
seeing that actor who has obtained this boon. But there is none to
speak of those accomplishments of mine to him, hearing which he
will come to me (52)".
The goose said:—O foremost of Asuras, that actor is an
appreciator of merits. Hearing of accomplished persons he travels
over the seven insular continents. O great Asura, if he hears of your
great accomplishments, know him as already arrived here (53-54).
Vajranabha said:—"O auspicious daughter of a bird, O goose!
may good betide you. Do you so arrange that the actor may come
here" (55).
Thus despatched on an errand by Vajranābha, the swans went
to Krishna and the king of gods and communicated to them every
thing (56). Hearing it Adhokshaja engaged Pradyumna in the work
of acquiring Prabhāvati and killing Vajranābha (57). O descendant of
Bharata, resorting to his celestial Māyā Hari sent the Bhaimas there
disguised as actors (58).
They dressed Pradyumna as the hero, Shāmva as his fool, Gada
as his companion and dressed other Bhaimas with becoming
dresses. Leading dancing girls were the fit heroines of that party.
The actor Bhadra and his party were also suitably dressed.
Thereupon ascending the cars driven by Pradyumna, the great car-
warrior Yadavas set out on the mission of the highly powerful
celestials. O king, at that time they all assumed the semblances of
men and women as necessary though they were men. Thereupon
they arrived at Supura, a dependant city of Vajra (59–63).
CHAPTER CCXL. THE YADAVAS ARRIVE AT THE
CITY OF ASURAS AS ACTORS.

Vaishampāyana said:—Thereupon king Vajramābha ordered the


Asuras living in their own cities, "Give them most excellent rooms
(1). Treat them as guests, give them various jewels and various
raiments which please people (2)." Receiving the order of their Chief
they did all this. And arriving there, the actors too, heard of before,
excited their curiosity (3). With great delight they welcomed the
actor with presents of jewels (4). Thereupon the actor, who had
obtained the boon, pleased highly the citizens of Supura with his
dancing (5). They gave a performance of the great epic Rāmāyana:
the birth of the incomparable Vishnu for the destruction of the king
of Rakshasas (Ravana) (6). How Lomapāda and Dasharatha had
brought for Shānta, the Muni Rishwashringa through prostitutes (7).
In that performance the actors so perfectly personated the
characters of Rāma, Lakshmana, Shatrughna, Bharata,
Rishwashringa and Sānta, that even the elderly Dānavas were
startled and spoke repeatedly of the similarity of their appearances
(8–9). Seeing their dresses, acting, entrance and introduction the
Dānavas were filled with wonder. With particular parts of the
performance the Asuras were so much pleased and attracted that
they repeatedly rose up, expressed their appreciation and gave away
charming necklaces of gold and Vaidurja, bracelets and cloths. After
receiving their remuneration the actors, with separate slokas,
eulogised the Asuras in order of their family and birth (9-13). O king,
afterwards the inhabitants of the dependant cities communicated to
Vajra nābha the arrival of the beautiful actors (14). O Bhārata, the
king of Daityas had already heard of it. Now pleased he sent a
messenger to bring the actor. At the mandate of the king of
Dānavas, the Daityas, living in branch cities, took the Yadavas,
disguised as actors, to the charming city of Vajra (15-16). For their
accomodation, a beautiful house, built by the celestial architect, was
offered, and necessary articles, by hundreds, were given them (17).
There upon having set up a beautiful pandal the great Asura,
Vajranābha, made a great festival with the actors (18). After they
had been relieved of toil the highly powerful Vajranābha gave
profuse jems and requested them to begin the play (19). O king,
having kept the women of his family behind a screen at a place from
which they could see all, the great Asura himself sat with his
kinsmen (20). Then dressing themselves as actors, and arranging for
the concert the Bhaimas, of dreadful deeds, went on with the
performance (21). They first played various tunes on musical
instruments, as Kansya, Venu, Muraja etc. Afterwards the women,
brought by the Bhaimas, sang the Gandharva song Chhalikya,
delightful to the mind and ears (22–23). Then with seven scales,
Gāndhāra and others, three Grāmas, and with Rāgas, Vasanta and
others, they sang sweetly the song of the sacred discension of
Ganga (24). Hearing that sweet song of the coming down of Gangā
set in time and tune Asuras rose up again and again and pleased the
actors (25). For some business the powerful Pradyumna, who had
assumed the guise of an actor, Gada and Shāmva conducted the
Nāndi.306 After the termination of the Prologue Rukshmini's son sang
the hymn, accompanied with beautiful gestures, of the descension of
Gangā. Afterwards they began the performance of the drama
Rambhābhisara,307 Shura acted the part of Rāvana, Monovati
represented Rambhā, Pradyumna Nalakuvara and Shāmva his
Vidushaka308 By their illusory powers the Yādavas represented the
scene of Kailāsha (26-29). They acted how the wicked Rāvana was
imprecated by Nalakuvara, worked up with anger and how Rambhā
was consoled (30). After the performance of this drama, the glory of
the high-souled Nārada by the heroic Yādavas, the Dānavas were
pleased with the dancing of the highly powerful Bhaimas. They gave
them costly apparels, jewelleries, necklaces set with costly jems,
beautiful balloons, cars ranging in the sky, elephants coursing in the
etherial region, cool and celestial sandal, Agura, and other scents
and the valuable jem Chintāmani which gives all that is thought of.
Giving away presents in this way at every scene those Dānavas were
deprived of their riches and jewels. Even the women of the Danava-
Chiefs shared the same fate (31–37).
On the other hand, Prabhāvati's friend Suchimukhi said to her:
—"O you of fair beauty, I had gone to the charming city of Dwārakā
protected by the Bhaimas. O you of sweet smiles and beautiful eyes,
I saw Pradyumna there secretly and told him about your love for
him, O you having lotus eyes. Pleased he has appointed this evening
for meeting you (38–40). O you of a beautiful waist, the Bhaimas
never speak an untruth; verily to-day you will meet your love" (41).
Hearing it Prabhāvati, filled with joy, said to the goose:—"O fair lady,
to-day wait in my room and sleep here. If you live by me I do not
fear any body. With you I wish to see Keshava's son." The goose
said to her lotus eyed friend Prabhāvati "So it will be." Afterwards
with Prabhāvati, she went up to her quarters (42–44).
Thereupon in the upper storey of that house constructed by the
celestial Architect, Prabhāvati began to make arrangements against
Pradyumna's arrival. After the completion of the arrangements, the
goose, with Prabhāvati’s permission, went away speedily like air for
bringing Kāma. Going to Kāma who was living in the guise of an
actor that one of sweet smiles said "You will see her to night". And
returning speedily she said to Prabhāvati, "O you of expansive eyes,
console yourself; Rukshmini's son is coming" (45–48). Thereupon
seeing a fragrant garland filled with bees carried for Prabhāvati, the
highly powerful and self-controlled hero, Pradyumna, the slayer of
his enemies, sat there on assuming the form of a bee. That garland,
covered with black-bees, was taken by the maid servants to the
inner appartment and kept near Prabhāvati. O gentle king, when
gradually evening set in, the other bees fled away. Then having none
to follow him the heroic Bhaima chief slowly sat on Prabhāvati's ear
(49-53).
Thereupon beholding the highly charming full moon arise there
Prabhāvati, a clever speaker, said to the goose, "O friend, my limbs
are burning, my mouth is being dried up and my heart is filled with
curiosity. What is the name of this disease? The newly-risen full
moon of cool-rays is liked by all. It is still creating anxiety in me as if
it is not liked by me. Oh fie on the nature of a woman! I have not
seen him—I have wanted him after only hearing of him—still my
limbs are burning. I am saying so of my own accord lest my love
may not come. Alas! If he does not come I will meet the same fate
with the silly lily. Alas! Although I am self-controlled still I have been
bitten by serpent-like Cupid (54–58). The rays of the moon are by
nature cool, delightful and charming. But, wonder, they are
scorching my body. The wind, carrying the filaments of various
flowers, is cool by nature, still it is scorching my beautiful frame like
forest-fire (59–60). I am thinking of being patient, but my weak
mind, shattering my resolution, does not allow me to do so.
Forsooth, losing control over my mind, I will run mad and be killed,
for my heart is trembling and I am looking again and again wildly
(61–62)".

[306] Eulogium of a king or praise of a deity recited in


benedictory verses at the commencement of a religious
ceremony or the opening of a drama.

[307] A drama describing the going away of Rambha in search of


her lover.

[308] Something like a fool attached to the Royal Courts.


CHAPTER CCXLI. PRADYUMNA APPEARS
BEFORE PRABHAVATI AND MARRIES HER.

Vaishampāyana said:—Afterwards thinking "This maiden has been


completely possessed by me." Krishna's son delightedly said to the
goose:—"Tell the daughter of the Daitya king, that in the guise of a
black-bee, I have come here along with other black-bees, attached
to the garland (1-2). I am now at present under her command. Let
her do what she likes to do with me." Saying this, the beautiful
husband of Rati appeared there in his own form (3). At that time the
house was lighted up with the effulgence of the person of the
intelligent Madana. And the beautiful rays of the moon were put to
shame (4). As the lord of waters (the ocean) rises with the lord of
night (moon) on a Parva day, so Prabhāvati's ocean of love increased
on seeing Kāma (5). Then turning her eyes a little with bashfulness,
Prabhāvati, having eyes like lotuses, sat there with her face cast
down (6). Seeing it Pradyumna held, with his own, the hands of
thin-built and beautiful Prabhāvati bedecked with handsome
ornaments. Then with hairs of his body standing erect he said:
—"Why have you cast down your face resembling the full-moon and
acquired after desiring for it a hundred times? Why do you not speak
with me (7-8) O you of a fair face, do not crush the effulgence of
your countenance. Cast off your fear and favour this servant of
yours. There is no more time, O timid girl. The hour for my return
has well-nigh arrived. I pray to you with folded hands, shake off
your fear. As you are peerless in beauty and fidelity so according to
the condition of time and place favour me by a Gandharva marriage"
(9-11).
Thereupon touching fire existing in the jem (he put on) and
reciting the mantra the Bhaima hero Pradyumna performed the
Homa ceremony with flowers. Thereupon holding Prabhāvati by the
arm embellished with most excellent ornaments he circumambulated
the fire of the jem (12–13). O king, at that time to keep the honor of
Achyuta’s son, Hutāshana, the divine lord of effulgence, the witness
of virtue and sin in the world, blazed up. Thereupon settling in his
mind about the Dahshinā (money-gift) the heroic descendant of
Yadu said to the goose:—"O bird, remaining at the gate, do you
guard us" (14–15). Hearing it the goose saluted him and went away.
Afterwards spending the whole night he, early in the morning, went
to the theatre. Although reluctant Prabhāvati gave him farewell, and
he too, thinking in his mind of the beauty of his love, went away.
Thus awaiting the orders of Indra and Keshava, the Bhaimas, for the
great work, lived there disguised as actors. Keeping the secret close
those high-souled ones awaited the hour when Vajranābha would go
out for conquering the three worlds. O king, as long as Kashyapa
was engaged in his sacrifice so long there did not take place any
dissension between the high-souled and virtuous celestials and the
Asuras ready for conquering the three worlds (16–24).
Thus while the intelligent Yādavas were waiting there for the
proper hour there appeared the rainy season delightful to all
creatures (25). The swans, fleet like the mind, used daily to carry
the intelligence of the highly powerful princes to Shakra and
Keshava. Thus well protected by those Dhārtarashtras the highly
powerful Pradyumna used to spend every night with the beautiful
Prabhāvati (26–27). The Asuras, possessed by Death, could not
perceive that they had been surrounded by the swans and actors in
the city of Vajra at the command of Vāsava (28). By and by, well
protected by the swans the heroic son of Rukshmini began to spend
even the day in Prabhāvati's house (29). O descendant of Kuru, on
account of his illusory powers, one half of his body used to appear
on the stage—and with the other half he lived with Prabhāvati. The
Asuras used to envy the high-souled Yadavas for their prosperity,
humility, character, sportiveness, cleverness, simplicity and learning.
Their women used to envy the Yādava women for their beauty,
luxury, scents, pure words and conduct (30–32).
O king, Vajranābha's illustrious brother Sunābha had two
beautiful and accomplished daughters—one of them was named
Chandravati, and the other Gunavati. They daily used to go to
Prabhāvati's house (33–34). One day seeing Prabhāvati engaged in
love affairs in her house they asked her about it on account of their
confidence in her love for them (35). She said:—"I possess a
learning which can soon bring a desired-for husband and gives
prosperity. It has such a wonderful power, that whoever, may he be
a Dānava or god, is thought of he at once comes losing all control
over himself. By the power of this learning I sport with the son of a
god. See, by my power, Pradyumna has become my most favourite."
Seeing him, endued with beauty and youthfulness, they were filled
with wonder (36–38). Afterwards smiling gracefully the beautiful
Prabhāvati again addressed to her sisters words suited to the time:
—"The gods are always engaged in virtuous acts, ascetic penances
and are truthful: on the other hand the great Asuras are haughty,
fond of pleasures and untruthful. So the gods are superior, for
victory is there where reign virtue, asceticism and truth (39–41). I
will instruct you in this learning; you may select two celestial youths
as your becoming husbands. By my power you will soon get them"
(42).
Hearing it the two sisters said to Prabhāvati having beautiful
eyes "So it will be." Thereupon when the honorable daughter of
Vajranābha asked Pradyumna about it he mentioned the names of
his uncle Gada and the hero Shāmva for both of them were
beautiful, accomplished and valiant (43-44).
Prabhavati said:—Formerly pleased with me Durvāsa conferred
on me this learning: it gives good luck and always preserves
maidenhood (45). The great saint said: "He, whom amongst the
gods, Dānavas and Yakshas you will think of, will be your husband. I
desired for this hero. Do you take this learning and you will in no
time be united with your loves."
Thereupon, O king, those two beautiful daughters of Sunābha,
filled with joy, accepted the learning from the mouth of their sister
and practised it. Then they thought of Gada and Shāmva. Covered
with illusion by Pradyumna those two heroic Bhaimas entered there
with him. Those two heroes, fond of the pious and the slayers of
their enemies, espoused them according to Gandharva rites after
reciting the mantras. Of them Gada married Chandravati and
Keshava's son Shāmva Gunavati. Thus awaiting the orders of Sakra
and Keshava those leading Yadus lived there happily with Asura girls
(46-51).
CHAPTER CCXLII. A DESCRIPTION OF THE
RAINY SEASON.

Vaishampāyana said:—In the rainy season, while looking at the sky


filled with clouds Kāma having, a countenance like the full moon,
said to Prabhāvati of beautiful eyes: "O fair lady, see there appears
the moon of beautiful rays covered with clouds like your face
covered with hairs. O you of fair eye-brows, see the lightning on the
cloud looks beautiful like your handsome gold ornament. O you of
fair limbs, the clouds are discharging torrents of rain like unto your
necklace (1-3). The cranes, emerging in the drops of water, are
shining like the rows of your teeth. O you of fair eye-brows, the
lotuses being under water, the tanks full of streams do not look
beautiful (4). The clouds adorned with crane, like beautiful and clean
teeth, are appearing like elephants, with huge tusks, about to fight
with one another in the forest (5). O you of beautiful limbs, like unto
circlets on your forehead the three coloured rain-bow, adorning the
sky and clouds, is gladdening the damsels (6). Expanding their large
feathers, the pea-hens looking perfectly beautiful in the company of
their mates and delighted at the muttering of clouds, are dancing
and emitting notes in return (7). Displaying their charming beauty
for a moment on the turrets other peacocks are dancing on the roofs
of the houses, white like the moon (8). With their feathers
exhausted, the beautiful peacocks, adorning for a moment the tops
of the trees, are again going to the naked ground in fear of new
grown-grass (9). The delightful wind, proceeding from cool drops of
rain, like sandal-paste, is blowing carrying the fragrance of Sarjā and
Arjuna flowers the very friend of Cupid (10). O you of a fair body,
had not this wind brought new showers and removed the exhaustion
of sporting it would not have been so much liked by me (11). What
is dearer to men in this season of the union of lovers than the
approach of this fragrant wind (12)? O you of fair body, beholding
the banks of the river overflown with water swans exhausted, and
united with Sārasas and Krounchas, are delightfully going to find out
quarters after their heart (13). O you of beautiful eyes, on the
departure of the Swans and Sarāsas emitting notes like the clatter of
car-wheels, the rivers and tanks, shorn of beauty, do not appear
charming any more (14). The goddess sleep, informed of the true
character of the rainy season and Hari, having saluted the most
beautiful Sree, has sought refuge with Upendra, the lord of the
world, lying down for rest in the celestial region (15). O you having
lotus eyes, the divine Upendra having fallen asleep the shining
moon, covered with cloth-like cloud, is imitating the colour of his
countenance (16). Seeking to please Krishna, all the seasons are
showering all sorts of flowers and bringing garlands of Kadamva,
Neepa, Arjuna and Ketaka (17). All the flowers, and trees, with the
elephants, having their faces soiled with poison, and filled with bees,
are exciting great curiosity in men (18). As if seeing the sky, pressed
down by the weight of clouds surcharged with water, your beautiful
face, breast and thighs have entered into a ditch (19). Beholding
these charming clouds as if adorned with garlands of cranes it
appears that they are showering grains on earth for the behoof of
the world (20). As a powerful king makes the infuriated wild
elephants fight with his own so the wind is setting clouds surcharged
with water against one another (21). The clouds are pouring
unearthly water, purified by air and delightful to sparrows, peacocks
and other birds sprung from eggs (22). As the twice-born ones, fond
of truth and religion, recite the Riks encircled by their pupils, so the
bulls are roaring with cows in the pasture ground (23). One of the
virtues of the rainy season is that women take pleasure in living
always in the company of their lovers (24). O beautiful lady, the only
defect that I perceive of the rainy season is that the moon,
resembling your countenance, does not come in view, having his
body possessed by the cloud-like Graha (25). In this season when
the moon appears in view at the interval of an approaching cloud,
the people, as if with delight, behold a friend returning from a
foreign country (26). Their eyes, on beholding the moon, the witness
of the lamentations of women suffering from separation, enjoy that
festivity which those of the women, separated from their lovers, do
on seeing them. So it appears to me: but this is not the fact (27).
The view of the moon is like a festival to the eyes of those women
who are united with their lovers, and is like a forest-fire to those
who suffer from separation, so the moon is the source of both
pleasure and pain to women (28). In your father's city there is the
effulgence of the rays of the moon even in its absence; so you
cannot form an idea of the merits and demerits of the moon and for
this I praise him before you (29). By practising hard austerities
which are resorted to by the pious he has attained to the region of
Brahmā which others can with difficulty acquire and is worshipped
by all. The Brāhmanas celebrate the glories of the great Soma in
sacrifice with Sāman verses (30). When the sacrificial fire was being
brought by Pururavā from the region of the Gandharvas it was
spoiled on the way. While searching that place a fig-tree was seen.
Collecting fuels from that tree the three fires were engendered. So it
is that the moon, the lord of trees and herbs, revived the spoiled fire
from the fig-tree. Chandra (the moon) is the father of Budha, the
author of most excellent deeds whose son was the king Pururavā
(31). O beautiful lady, formerly when his ambrosial body was drunk
by the dreadful Munis the high souled Soma desired for Urvasi, the
foremost of Apsaras (32). In his family the intelligent Ayu attained to
the celestial region, through the tips of the Kusa grass and secured
the dignity of a demi-god and the heroic Nahusa acquired the dignity
of the king of gods (33). The moon, in whose family, the Divine Lord
Hari, the creator of the world is born, for a work of the gods, as a
Bhaima chief, remains always encircled by the daughters of Daksha
(34). In his family was born the high-souled Vasu, as if the flag of
his race, who, by his deeds, attained to the dignity of a Lord
Paramount; the king Yadu, the foremost of the lunar race, in whose
family, the Bhojas, resembling the king of gods, were born and who
became the Lord Paramount, was also born in the family of the
moon (35–56). O you having lotus eyes, in Yadu's family, born in the
lunar race no king has been born who is wily, atheistic, unrespectful,
ugly and coward (37). You are the daughter-in-law of an
accomplished prince as you are the mine of accomplishments.
Therefore bow unto Iswara fond of the pious. O lady, the foremost
of Purusha Nārāyana, the refuge of the grand-father, the gods and
the worlds, is your father-in-law. Bow unto him (38-39)".
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like