100% found this document useful (1 vote)
15 views

Professional Design Patterns in VB NET Building Adaptable Applications 1st Edition Tom Fischer pdf download

The document is a comprehensive guide to design patterns in VB.NET, aimed at building adaptable applications. It covers various design patterns across different tiers, including data, middle, and presentation tiers, along with practical examples and UML diagrams. The book includes contributions from multiple authors and provides resources for further learning and application development.

Uploaded by

diefhsha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
15 views

Professional Design Patterns in VB NET Building Adaptable Applications 1st Edition Tom Fischer pdf download

The document is a comprehensive guide to design patterns in VB.NET, aimed at building adaptable applications. It covers various design patterns across different tiers, including data, middle, and presentation tiers, along with practical examples and UML diagrams. The book includes contributions from multiple authors and provides resources for further learning and application development.

Uploaded by

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

Professional Design Patterns in VB NET Building

Adaptable Applications 1st Edition Tom Fischer


pdf download

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

Get Instant Ebook Downloads – Browse 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 orders@springer-ny.com, or visit


http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, email
orders@springer.de, 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 info@apress.com, 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 atjcslater@hotmail.com.

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 Chauratcha_urwu@hotmail.com.

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 e-mailingsupport@apress.com. 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
Another Random Document on
Scribd Without Any Related Topics
For reading, Agathokles.
For rhapsody, Miltiades.
For playing lyre with fingers, Xenon.
For playing lyre, Kleoites.
Long Distance Race (varied from
2¼ miles to about ¾ mile).
Boys Asklepiades.
Junior epheboi Dionusios.
Middle ” Timokles.
Senior ” Moschion.
Men ” Aischrion.

Stadion (200 yards).


Boys Athenikon.
Junior epheboi Hestiaios.
Middle ” Apollonios.
Senior ” Artemon.
Men ” Metrodoros.

Diaulos (400 yards).


Boys Athenikon.
Junior epheboi Hubristos.
Middle ” Melantes.
Senior ” Apollonios.
Men ” Menis.
(Apollonios seems to
have been so good
that, though a
middle ephebos, he
competed in and
won the senior
ephebos’ race here,
unless there were
two boys of the
same name.)

Wrestling.
Boys Athenikon.
Junior epheboi Demetrios.
Middle ” Moschos.
Senior ” Theodotos.
Men ” Apellas.

Boxing.
Boys Herakleides.
(The rest is wanting.)
(Notice the three victories of the boy
Athenikon.)
At Thespiai in Boiotia[166] there were prizes for senior and junior
boys in the various races, and in boxing, wrestling, pankration, and
pentathlon, besides open prizes for poetry and music of all kinds.
Attic inscriptions arrange the events thus[167]:—

Stadion.
Junior Boys.
Middle Boys.
Senior Boys.
Boys Open.
Men.
Diaulos.
Junior Boys.
Middle Boys.
Senior Boys.
Boys Open.
Men.

Fighting in Heavy Arms.


Junior Boys.
Middle Boys.
Senior Boys.
Epheboi.
The Olympian and Pythian festivals, however, had only a single
series of contests for boys:—

Olympia.
Boys. Stadion (Pind. Ol. xiv.).
Boxing (Pind. Ol. x., xi.).
Wrestling (Pind. Ol. viii.).
(only in 628 B.C.) Pentathlon.
(not till 200 B.C.) Pankration.

Pythia.
Boys. Long Distance Race.
Diaulos (400 yards) (Pind. Puth. x.).
Stadion (200 yards) (Pind. Puth. xi.).
Boxing.
Wrestling (Bacchul. xi.).
Pankration (not till 346 B.C.).
But at Nemea both pentathlon[168] and pankration[169] for boys had
already been established by Pindar’s time, as well as the more usual
contests.[170]
How far individual schoolmasters, as distinct from the State, gave
prizes to their pupils, is little known; an epigram in the Anthology
supplies the only evidence, by narrating that “Konnaros received
eighty knucklebones because he wrote beautifully, better than the
other boys.”[171] But probably as a general rule the task of rewarding
merit was left to the public contests.
*****
Thus the State did much to encourage, if it did little to assist or
enforce, education. With such splendid rewards before them, boys
were probably quite eager to attend school, or at any rate the
palaistra. As soon as they were old enough to go to school,[172] they
were entrusted to an elderly slave,[173] who had to follow his master’s
boys about wherever they went and never let them go out of his
sight.[174] This was the paidagogos—a mixture of nurse, footman,
chaperon, and tutor—who is so prominent a figure on the vases and
in the literature of classical Hellas. There was only one for the family,
so that all the boys had to go about together and to attend the same
schools and the same palaistrai at the same time.[175] He waited on
them in the house, carried their books or lyres to school, sat and
watched them in the schoolroom, and kept a strict eye upon their
manners and morality in the streets and the gymnasia. Thus, for
instance, in Plato, Lusis and Menexenos have their paidagogoi in
attendance at the palaistra, who come and force them away from
the absorbing conversation of Sokrates, when it is time for them to
go home.[176] On a vase these attendants may be seen sitting on
stools behind their charges, in the schools of letters and music, with
long and suggestive canes in their hands.[177] A careful parent would,
of course, see that a slave who was to occupy so responsible a
position was worthy of it: but great carelessness seems often to
have been shown in this matter. The paidagogoi of Lusis and
Menexenos, boys of rank and position, had a bad accent, and on a
festival day, it is true, were slightly intoxicated.[178] Plutarch notices
that in his time parents often selected for this office slaves who were
of no use for any other purpose.[179] Xenophon, feeling the demerits
of the Athenian custom, commends the Spartans, who entrust the
boys not to slaves, but to public officials of the highest rank.[180] But
in well-regulated households the paidagogos was often a most
worthy and valuable servant. Sikinnos, who attended the children of
Themistokles in this capacity, was entrusted by his master with the
famous message to Xerxes, which brought on the battle of Salamis;
he was afterwards rewarded with his freedom, the citizenship of
Thespiai, and a substantial sum of money.[181] The custom of
employing these male-nurses dated back to early times at Athens:
for Solon made regulations about them.[182]
Boys were entrusted to paidagogoi as soon as they went to
school at six. This tutelage might last till the boy was eighteen[183]
and came of age; but more frequently it stopped earlier. Xenophon,
[184] in his wish to disparage everything not Spartan, declares that in

all other States the boys were set free from paidagogoi and
schoolmasters as soon as they became μειράκια, i.e. at about
fourteen or fifteen. The conjunction of schoolmasters suggests the
explanation of the variations in age. When an elder brother ceased
to attend school, and his younger brothers were still pursuing their
studies, there being only one paidagogos, he had to be left
unattended. But in cases where there was only one son, or where
the eldest of several stayed on at school until he came of age, he
would have the paidagogos to attend him until he was his own
master.
The life of such an attendant must have been an anxious one in
many cases. Plato compares his relations towards his charges with
the relations of an invalid towards his health: “He has to follow the
disease wherever it leads, being unable to cure it, and he spends his
life in perpetual anxiety with no time for anything else.”[185] With
unruly boys of different ages, and consequently of different tastes
and desires, the slave must have been often in a difficult position.
He had, however, the right of inflicting corporal punishment.
The chief object of the paidagogos was to safeguard the morals
of his charges. Boys were expected to be as modest and quiet in
their whole behaviour, and as carefully chaperoned, as young girls.
Parents told the schoolmasters to bestow much more attention upon
the boy’s behaviour than upon his letters and music.[186] This attitude
was characteristic of Athens from the first. The school laws of Solon,
as quoted by Aischines, deal wholly with morality. He gives the
following account of them[187]:—
“The old lawgivers stated expressly what sort of life the
free boy ought to lead and how he ought to be brought up;
they also dealt with the manners of lads and men of other
ages.” “In the case of the schoolmasters, to whom we are
compelled to entrust our children, although their livelihood
depends upon their good character, and bad behaviour is
ruinous to them, yet the lawgiver obviously distrusts them.
For he expressly states, first, the hour at which the free boy
ought to go to school; secondly, how many other boys are to
be present in the school; and then at what hour he is to
leave. He forbids the schoolmasters to open their schools and
the paidotribai their palaistrai before sunrise, and orders them
to close before sunset, being very suspicious of the empty
streets and of the darkness. Then he dealt with the boys who
attended schools, as to who they should be and of what
ages; and with the official who is to oversee these matters.
He dealt too with the regulation of the paidagogoi, and with
the festival of the Muses in the schools and of Hermes in the
palaistrai. Finally, he laid down regulations about the joint
attendance of the boys and the round of dithyrambic dances;
for he directed that the Choregos should be over forty.”
“No one over the age of boyhood might enter while the
boys were in school, except the son, brother, or son-in-law of
the master: the penalty of infringing this regulation was
death. At the festival of Hermes the person in charge of the
gymnasium[188] was not to allow any one over age to
accompany the boys in any way: unless he excluded such
persons from the gymnasium, he was to come under the law
of corrupting free boys.”
It will be noticed that these regulations are entirely concerned
with morality: they safeguard an existing system. They prescribe
neither the methods nor the subjects of education; for with such
matters the Athenian government did not interfere. But over the
question of morals it becomes unexpectedly tyrannous, and makes
the most minute regulations worthy of the strictest bureaucracy. It
interfered on this point in other ways also. The solemn council on
the Areiopagos had a special supervision over the young, from
Solon’s time onward; this was partially taken away from it by
Ephialtes and Perikles, but the Axiochos shows that, though in
abeyance, it continued to exist; in the middle of the fourth century,
however, Isokrates laments that it had fallen into disuse.
The Axiochos also states that the ten Sophronistai, elected to
guard the morals of the epheboi, exercised control over lads also.
These officials probably took their rise in the days of Solon: the
regulation that they must be over forty harmonises with the other
enactments of those days; and, although they died out at the end of
the fourth century, they were revived under the Roman Empire. Now
it is most unlikely that the archaistic legislators of imperial times
would have revived an office which had only existed during the
closing decades of the fourth century. Solon is known to have
appointed a magistracy specially to deal with the children;[189] and, if
these magistrates were not the Sophronistai, all trace of his creation
has been lost, which is most unlikely to have happened. So the
Sophronistai probably date from early times. Their duty was a
general supervision of the morals of the young; their chief function
would be to prosecute, on behalf of the State, parents and
schoolmasters who infringed Solon’s moral regulations. But such
prosecutions would usually be undertaken by private individuals
concerned in the case, and so this magistracy tended to become a
sinecure. It may even have ceased to exist after the fall of the
Areiopagos. But it seems to have revived under the restored
democracy for a while (if the Axiochos belongs to Aischines the
Sokratic), to sink again in the middle of the century. At the close of
the century it revives once more with the changes in the ephebic
system, and finally perishes when the epheboi became too few to
need ten officers to supervise their morals. An account of the
Sophronistai of this later period will be given in connection with the
epheboi.
PLATE II.

THE FLUTE LESSON—THE BOY’S TURN


Wiener Vorlegeblätter, Series C, Plate 4.
From a Kulix by Hieron, now at Vienna.

The strategoi[190] exercised a superintendence over the epheboi


during their two years’ training as recruits, as would naturally be
expected. Late in the fourth century they appear also to have been
connected with the local schools in Attica; an inscription at Eleusis,
which Girard assigns to 320 B.C., thanks the strategos Derkulos for
the diligence which he had shown in supervising the education of
the children there.[191] Whether they exercised such functions in the
days when their military duties were more important, is more than
doubtful. But any Athenian magistrate could interest himself in the
schools, no doubt, and intervene to check abuses.[192]
*****
In the period of juvenile emancipation and increasing luxury and
indulgence for children which marked the closing decades of the fifth
century, it became customary for conservative thinkers to look back
with longing, and no doubt idealising, eyes to the “good old times.”
The sixth and early fifth centuries came, probably unjustly, to be
regarded as the ideal age of education, when children learned
obedience and morality, and were not pampered and depraved;
when they were beautiful and healthy, not pale-faced, stunted, and
over-educated.
Listen to Aristophanes,[193] yearning for “the good old style of
education, in the days when Justice still prevailed over Rhetoric, and
good morals were still in fashion. Then children were seen and not
heard; then the boys of each hamlet and ward walked in orderly
procession along the roads on their way to the lyre-school,—no
overcoats, though it snowed cats and dogs. Then, while they stood
up square—no lounging—the master taught them a fine old patriotic
song like ‘Pallas, city-sacker dread,’[194] or ‘A cry that echoes afar,’[195]
set to a good old-fashioned tune. If any one tried any vulgar trills
and twiddles and odes where the metre varies, such as Phrunis and
Co. use nowadays, he got a tremendous thrashing for disrespect to
the Muses.” While being taught by the paidotribes, too, they
behaved modestly, and did not spend their time ogling their
admirers. “At meals children were not allowed to grab up the
dainties or giggle or cross their feet.” “This was the education which
produced the heroes of Marathon.… This taught the boys to avoid
the Agora, keep away from the Baths, be ashamed at what is
disgraceful, be courteous to elders, honour their parents, and be an
impersonation of Modesty—instead of running after ballet-girls. They
passed their days in the gymnasia, keeping their bodies in good
condition, not mouthing quibbles in the Agora. Each spent his time
with some well-mannered lad of his own age, running races in the
Akademeia under the sacred olives, amid a fragrance of smilax and
leisure and white poplar, rejoicing in the springtide when plane-tree
and elm whisper together.” All the voices of generations of boys,
bound down to indoor studies when wood and field and river are
calling them, the complaint of ages of fevered hurry and bustle,
looking back with regret on the days of “leisure” and “springtide,”
seem to echo in Aristophanes’ lament for the ways that were no
more.
“This education,” he goes on, “produced a good chest, sound
complexion, broad shoulders, small tongue; the new style produces
pale faces, small shoulders, narrow chest, and long tongue, and
makes the boy confuse Honour with Dishonour: it fills the Baths,
empties the Palaistra.”
The next witness to be called is Isokrates. He is somewhat
prejudiced by his dream of restoring the Areiopagos to its old power,
but he is an educational expert and his evidence is supported by that
of many others. In the days when the Areiopagos had the
superintendence of morals, he says,[196] “the young did not spend
their time in the gambling dens, and with flute-girls and company of
that sort, as they do now, but they remained true to the manner of
life which was laid down for them.… They avoided the Agora so
much, that, if ever they were compelled to pass through it, they did
so with obvious modesty and self-control. To contradict or insult an
elder was at that time considered a worse offence than ill-treatment
of parents is considered now. To eat or drink in a tavern was a thing
that not even a self-respecting servant would think of doing then; for
they practised good manners, not vulgarity.”
Call Plato next.[197] “In a democratic state the schoolmaster is
afraid of his pupils and flatters them, and the pupils despise both
schoolmaster and paidagogos. The young expect the same
treatment as the old, and contradict them and quarrel with them. In
fact, seniors have to flatter their juniors, in order not to be thought
morose old dotards.”
The counts of the indictment are luxury, bad manners, contempt
for authority, disrespect to elders, and a love for chatter in place of
exercise. The old regime had strictly forbidden luxury. Warm baths
had been regarded as unmanly, and were even coupled with
drunkenness by Hermippos.[198] The boys had only worn a single
garment, the sleeveless chiton, a custom which survived till late
times in Sparta and Crete; but at Athens they began to wear the
ἱμάτιον or overcoat as well. Xenophon, blaming parents “in the rest
of Hellas” (i.e. elsewhere than in Sparta), says: “They make their
boy’s feet soft by giving him shoes, and pamper his body with
changes of clothes; they also allow him as much food as his stomach
can contain.”[199] Children began to be the tyrants, not the slaves, of
their households. They no longer rose from their seats when an
elder entered the room; they contradicted their parents, chattered
before company, gobbled up the dainties at table, and committed
various offences against Hellenic tastes, such as crossing their legs.
They tyrannised over the paidagogoi and schoolmasters. Alkibiades
even smacked a literature-master. A similar change came over the
position of children in England during the latter half of the
nineteenth century. If Maria Edgeworth could have met a modern
child, she would have uttered quite Aristophanic diatribes against the
decay of good manners.
With this change went a more serious matter, a change of tone.
Whether the old days were as moral as the conservatives supposed,
may be doubted; but the atmosphere of Periclean and Socratic
Athens, as represented by all its literary lights, was certainly most
unsuitable for the young. Perhaps general morality was no worse,
but the immorality was no longer concealed from the children. The
old laws which had excluded unsuitable company from the schools
and palaistrai were neglected, and these educational buildings
became the resort of all the fashionable loungers of Athens.
The preference given to conversation over exercise was a feature
of the age. In part, it was a preference for intellectual as against
purely physical education. The free discussion with children of ethical
subjects probably ceased with the death of Sokrates; this can hardly
be regretted, if Plato’s evidence as to the nature of Socratic
dialogues is to be believed. From the importance which Plato gives
to gymnastics as a corrective to exclusive μουσική even in the
education of his highly intellectual Philosopher-Kings, we may
suspect that the revolt against excessive athletics at Athens, of
which Euripides had been the leader, had gone too far, and that a
reaction was needed. Certainly the Athenians do not distinguish
themselves for pluck or energy in the fourth century: in Platonic
phrase, the temper of their resolution had been melted away by
their exclusive devotion to intellectual and artistic pursuits.
Let me close this subject, however, with a more pleasing picture
of that αἰδώς or modesty at which the older education had aimed. It
is taken from the midst of that brilliant but corrupt Socratic Athens.
[200] Young Autolukos had won the boys’ contest for the pankration at

the great Panathenaic festival. As a treat, Kallias, a friend of his


father, had taken him to the horse-races, and afterwards invited him
out to dinner with his father Lukon: such a dignity was rarely
accorded to an Athenian boy.
The boy sits at table, while the grown men recline. Some one
asked him what he was most proud of—“Your victory, I suppose?”
He blushed and said, “No, I’m not.” Every one was delighted to hear
his voice, for he had not said a word so far. “Of what then?” some
one asked. “Of my father,” replied the boy, and cuddled up against
him.
These shy, blushing boys were a feature of the age. The stricter
parents, knowing the dangers which surrounded their sons, tried to
keep them entirely from any knowledge or experience of the world.
*****
As far as can be discovered from the somewhat fragmentary
evidence, the Athenian type of education was prevalent throughout
the civilised Hellenic world, with the exception of Crete and
Lakedaimon, which had systems of their own. Xenophon, in praising
the Spartan system and contrasting it with that which was prevalent
in neighbouring countries, ascribes to what he calls “the rest of
Hellas” educational customs and arrangements exactly similar to
those which are found to have existed at Athens. His statement is
borne out by other evidence. Chios certainly had a School of Letters
before 494 B.C.; for a building of this sort collapsed in that year,
destroying all but one of the 120 pupils.[201] Boiotia, byword for
stupidity, had schools even in the smaller towns. A small place like
Mukalessos had more than one; for a detachment of wild Thracian
mercenaries in the pay of Athens fell upon the town at daybreak one
morning during the Peloponnesian War, and entering “the largest
school in the place,” killed all the boys.[202] Arkadia had an equally
bad reputation; yet, according to Polubios,[203] in every Arcadian
town the boys were compelled by law to learn to sing. Troizen must
have had schools in 480, when she provided them for her Athenian
guests. Aelian vouches for schools in Lesbos,[204] Pausanias[205] for a
school of sixty boys in Astupalaia in 496 B.C. The poet Sophocles
dined with a master of letters whose school was either in Eretria or
Eruthrai.[206] The inscriptions show that before the third century
there were flourishing schools in most of the islands.
Gymnastic education must have gone on in every Hellenic city, for
the athletic victors at the great games come from every part. Musical
training too was required for the dancing and singing which were
universal throughout Hellas; but how far the lyre was taught must
remain doubtful. In Boiotia the flute replaced the lyre in the schools.
But it may be taken for granted that letters, some sort of music, and
gymnastics were taught in every part of civilised Hellas, with the
possible exception that letters may not have been taught at Sparta.
Secondary Education, as long as it was supplied by the Sophists,
reached every village in the Hellenic world; later, it had a tendency
to be confined to the large towns. The Tertiary system of military
training and special gymnastics for the epheboi would seem, from
the scanty evidence of the inscriptions, to have been well-nigh
universal.
I will now proceed to give a more detailed account of the several
branches of this widespread educational system. As the evidence
comes almost entirely from Athens, my description will deal in the
main with Athenian education; but, as the same type prevailed
throughout the greater part of Hellas, the description may be taken
as applying to the other cities also.

[98] Herod. ii. 167. Corinth was an exception.


[99] Plato, Laws, 846 d.
[100] Arist. Pol. viii. 2. 4.
[101] Xen. Econ. iv. 3. Sitting was regarded as a slavish attitude, since
the free citizen mostly stood or lay down. Xen. Econ. iv. 3.
[102] Plato, Protag. 328 a.
[103] Xen. Revenues, ii. 2.
[104] Plato, Kleitophon, 409 b.
[105] Plato, Rep. 421 e.
[106] Plato, Gorg. 514 b.
[107] Plato, Rep. 467 a.
[108] Aristoph. Acharn. 1032.
[109] The fifth-century comic poet.
[110] Plutarch, Solon, 22.
[111] Plato, Laws, 643 e.
[112] Except possibly in Chios and Lokris, and of course in Sparta.
[113] Thuc. ii. 45. 4.
[114] Xen. Econ. vii. 5.
[115] Xen. Mem. ii. 7.
[116] Plato, Rep. 455 c.
[117] Plato, Laws, 805 e.
[118] As in Lusias, ag. Diogeiton, 32. 28.
[119] In the Econ. vii. 10.
[120] Thus the Axiochos (366 d) puts seven years as the age at which
grammatistai and paidotribai began. Plato (Laws, 794) says six; Aristotle
(Pol. vii. 17) about five; Xenophon (Constit. of Lak. ii.) “as soon as the
children begin to understand.”
Aesop was popular then, as now. This is the μουσική anterior to
[121]
γυμναστική, so keenly criticised in the Republic.
[122] Plato, Protag. 325 c-e.
[123] Xen. Mem. ii. 2. 6.
[124] Plato, Protag. 326 c.
[125] Aristotle, Pol. vii. 17. 7.
[126] The three in this order in Plato, Protag. 312 b, 325-326; Charmid.
159 c; Kleitoph. 407 c; Xen. Constit. of Lak. ii. 1; Isok. Antid. 267. The
first two in this order in Charmid. 160 a; Lusis, 209 b; inverted in Euthud.
276 a. Aristot. (Pol. viii. 3) gives γράμματα, γυμναστική, μουσική. Plato in
the Laws 810 a makes κιθαριστική follow γραμματική; Aristophanes
mentions the paidotribes just after the κιθαριστής.
[127] Aristot. Pol. viii. 3. 1.
[128] Xen. Constit. of Lak. ii.
[129] See Illustr. Plates I. a and I. b.
[130] Plato, Laws, 810 a.
[131] Vase B 192.
[132] Vases E 171, 172; see Plates III. and IV.
[133] Aristot. Pol. viii. 4. 9.
[134] Ibid. viii. 1. 2.
[135] [Plato] Rivals, 132 a.
[136] Plato, Lusis, 206 d.
[137] Plato, Laches, 179 a.
[138] Xen. Constit. of Lak. iii.
[139] Plato, Lusis, 214 b.
[140] Rhetoric is, of course, banished from a Platonic state.
[141] [Plato] Axiochos, 366 e.
[142] See Petit, Leges Atticae, ii. 4, compiled with great ingenuity out of
many authors. Hence the proverbs ὁ μήτε νεῖν μήτε γράμματα
ἐπιστάμενος, of utter dunce, and πρῶτον κολυμβᾶν δεύτερον δὲ
γράμματα. The spelling-riddles of the tragedians imply a whole nation
interested in spelling.
[143] Plato, Kriton, 50 d.
[144] Aristophanes, Knights, 189.
[145] Ibid. 1235-1239.
[146] Ibid. 987-996.
[147] [Plato] Theages, 122 e.
[148] Plato, Alkibiades, i. 122 b. The Athenian State, however, from the
time of Solon onwards, supported and educated at public expense the
sons of those who fell in battle. The endowed systems in Teos and at
Delphoi belong to the third century; it is impossible to say whether such
existed earlier.
[149] Xen. Mem. ii. 2. 6.
[150] [Xen.] Constit. of Athens, ii. 10.
[151] Plutarch, Alkib. 3; Plato, Charmides, 153 a.
[152] C.I.A. ii. 1. 444, 445, 446.
[153] See Excursus on γυμνιασιαρχοί.
[154] He could, and had to, use compulsion in collecting boys. This
suggests that a parent could always, if he wished, get this free education
for his son.
[155] This rule fell into abeyance.
[156] Dem. against Boiot. 1001.
[157] [Xen.] Constit. of Athens, i. 13.
[158] On the strength of the passages quoted from the law, and from
Demosthenes, and of Aristophanes, Clouds, 964, some have maintained a
theory that the Athenian tribes provided free education in dancing, and
perhaps in other subjects, to all free boys, exclusive of competitions. But
the quotation in Aischines, except for the actual law, which is a later
interpolation, certainly refers only to the choregoi, and the passage in
Demosthenes is concerned only with chorus-dancing for competitions. In
Aristophanes the boys of the same neighbourhood naturally attend the
same school, that is all.
[159] Plut. Themist. 10.
[160] Ael. Var. Hist. vii. 15.
[161] Diod. Sic. xii. 42.
[162] Probably lived circa 500 B.C.
[163] Plato, Tim. 21 b.
[164] Böckh, 3088.
[165] Ibid. 2214. I have omitted patronymics.
[166] C.I.G. Boeot. 1760-1766.
[167] Böckh, 232, 245.
[168] Pind. Nem. vii.
[169] Bacchul. xiii., Pind. Nem. v.
[170] Wrestling, Pind. Nem. iv., vi.
[171] Anthol. ed. Jacobs, vi. 308.
[172] Sometimes earlier. Plato, Protag. 325 c.
[173] Elderly, as in the picture of Medeia and her children given in
Smith’s Smaller Classical Dictionary under “Medea,” and on Douris’ Kulix,
Plates I. a and I. b (if those are paidagogoi), and on other vases.
[174] So Fabius Cunctator was called Hannibal’s paidagogos, because he
followed him about everywhere.
[175] There is only one for Lusis and his brothers (Plato, Lus. 223 a), for
Medeia’s two children (Eur. Med.), for two boys in Lusis, 223 a, and for
Themistocles’ children (Herod. viii. 75).
[176] Plato, Lus. 208 c. He is referred to as ὅδε, showing that he is
present.
[177] Illustr. Plates I. a and I. b. Perhaps only the walking-stick carried
by all Athenians.
[178] Plato, Lus. 223 a.
[179] Plut. Education of Boys.
[180] Xen. Constit. of Lak. ii. 2.
[181] Herod. viii. 75.
[182] Aisch. ag. Timarch. 35. 10.
[183]In the guardian’s accounts given by Lusias, ag. Diogeiton, 32. 28,
a paidagogos is paid for till the boy is eighteen; but there was a younger
brother, for whom he may have been required, so the elder may have
been free earlier. In Plautus (Bacch. 138) we find a paidogogos in
attendance till his charge was twenty.
[184] Xen. Constit. of Lak. iii. 1.
[185] Plato, Rep. 406 a.
[186] Plato, Protag. 325 d.
[187] Aischin. ag. Timarch. 9.
γυμνασιαρχής. See Excursus on γυμνασιαρχοί. This law was totally
[188]
neglected in Socratic Athens. See Plato’s Lusis.
[189]Aischin. ag. Timarch. 10. The word σωφρονιστής, in a general
sense, occurs three times in Thucydides.
[190] Deinarchos, ag. Philokles, 15.
[191] Girard, L’Éducation Athénienne, pp. 51, 52.
[192]The Archon Eponumos had the control of orphans and probably
intervened if their education was neglected.
[193] Aristoph. Clouds, 960 ff.
[194] By Lamprokles (476 B.C.).
[195] By Kudides (? = Kudias. Smyth, Melic Poets, p. 347).
[196] Isok. Areiop. 149 c, d.
[197] Plato, Rep. 563 a.
[198] Floruit 432 B.C. (in Athen. 18 c).
[199] Xen. Constit. of Lak. ii. 1.
[200] Xen. Banquet, iii. 13.
[201] Herod. vi. 27.
[202] Thuc. vii. 29.
[203] Pol. iv. 20. 7.
[204] Ael. Var. Hist. 7. 15.
[205] Pausan. vi. 9. 6.
[206] Athen. 604 a-b.
CHAPTER III

ATHENS AND THE REST OF HELLAS:


PRIMARY EDUCATION

We have seen that Primary Education in Hellas consisted of letters


and music, with a contemporary training in gymnastics; to which
triple course was added, late in the fourth century, drawing and
painting. How the day was divided between mental and physical
training is unknown—probably, like everything else, this varied with
the taste of the individual—but the following sketch from Lucian,[207]
although it belongs to a much later date, may perhaps give some
idea of a schoolboy’s day:—
“He gets up at dawn, washes the sleep from his eyes, and
puts on his cloak. Then he goes out from his father’s house,
with his eyes fixed upon the ground, not looking at any one
who meets him. Behind him follow attendants and
paidagogoi, bearing in their hands the implements of virtue,
writing-tablets or books containing the great deeds of old, or,
if he is going to a music-school, his well-tuned lyre.
“When he has laboured diligently at intellectual studies,
and his mind is sated with the benefits of the school
curriculum, he exercises his body in liberal pursuits, riding or
hurling the javelin or spear. Then the wrestling-school with its
sleek, oiled pupils, labours under the mid-day sun, and
sweats in the regular athletic contests. Then a bath, not too
prolonged; then a meal, not too large, in view of afternoon
school. For the schoolmasters are waiting for him again, and
the books which openly or by allegory teach him who was a
great hero, who was a lover of justice and purity. With the
contemplation of such virtues he waters the garden of his
young soul. When evening sets a limit to his work, he pays
the necessary tribute to his stomach and retires to rest, to
sleep sweetly after his busy day.”
The school hours were naturally arranged to suit the times of
Hellenic meals, for which the boys returned home. The ordinary
arrangement was a light breakfast at daybreak, a solid meal at mid-
day, and supper at sunset. So the schools opened at sunrise.[208]
Solon enacted that they should not open earlier. They closed in time
to allow the boys to return home to lunch,[209] opened again in the
afternoon, and closed before sunset.[210] How many of the
intermediate hours were spent in work,[211] and what intervals there
were, is unknown. There was, of course, no weekly rest on Sundays;
but festivals, which were whole holidays, were numerous throughout
Hellas, and, in Alexandria at any rate, on the 7th and 20th of every
month the schools were closed, these days being sacred to Apollo.
[212] There were also special school festivals, such as that of the

Muses, and holidays in commemoration of benefactors; thus


Anaxagoras left a bequest to Klazomenai, on condition that the day
of his death should be celebrated annually by a holiday in the
schools.[213] It must also be remembered that one of the three
branches of Primary Education in Hellas would be called play in
England: an afternoon spent in running races, jumping, wrestling, or
riding would not be regarded as work by an English schoolboy.
Music, too, is usually learned during play-hours in an English school.
Even Letters, when the elementary stage was past, meant reciting,
reading, or learning by heart the literature of the boy’s own
language, and most of it not stiff literature by any means, but such
fascinating fairy-tales as are found in Homer. There is little trace of
Hellenic boys creeping unwillingly to school: their lessons were made
eminently attractive.
Of the fees which were paid to schoolmasters little is known. An
amusing passage in Lucian,[214] dealing with the under-world,
describes those who had been kings or satraps upon earth as
reduced in the future state “to beggary, and compelled by poverty
either to sell kippers or to teach the elements of reading and
writing.” From this it may be inferred that elementary schoolmasters
did not make much money by their fees. This inference is supported
by the fact that even the poorest Athenians managed to send their
sons to such schools. Plato in the Laws reserves the profession for
foreigners, thus suggesting that it was neither well paid nor highly
esteemed. To call a man a schoolmaster was almost an insult;
Demosthenes, abusing Aischines, says, “You taught letters, I went to
school.”[215] The weakness of the masters’ position may be seen too
from the extreme contempt with which their pupils seem to have
treated them. The boys bring their pets—cats and dogs and leopards
—into school, and play with them under the master’s chair.
Theophrastos,[216] in describing the characteristics of the mean man,
says that “he does not send his children to school all the month of
Anthesterion” (that is, from the middle of February to the middle of
March) “on account of the number of feasts.” The school-bills were
paid by the month, and, since boys did not go to school on the great
festivals, and Anthesterion contained many such days, the mean
parent thought he would not get his money’s worth for this
particular month, and so withdrew his boys while it lasted.
Mean parents also deducted from the fees in proportion, if their
sons were absent from school owing to ill-health for a day or two;
[217]
but this was not usually done. The bills were paid on the 30th of
each month.[218] Schoolmasters apparently had some difficulty in
getting their bills paid at all; according to Demosthenes’ statement,
his bills were never paid, owing to the fraudulent behaviour of his
guardian Aphobos.[219]
No doubt the fees varied according to the merits of the school, for
the schools at Athens seem to have differed greatly. Demosthenes,
when boasting of his career, in his speech On the Crown, says that
he went as a boy to the respectable schools;[220] the quality and
quantity of the teaching must have been varied to suit the parent’s
pocket. For the poor there would probably be schools where only the
elements of reading and writing were taught. In the higher class of
school these elements would be taught by under-masters, frequently
slaves; but free citizens might also be reduced by poverty to take
such a post. This may be seen from the case of the father of
Aischines, the orator.[221] Impoverished and exiled like many
democrats by the Thirty Tyrants, he returned with the Restoration a
ruined man. To earn his living, he became an usher at the school of
one Elpias, close to the Theseion, and taught letters: his son
Aischines seems to have begun his life by assisting his father in this
occupation. His opponent, Demosthenes, takes advantage of the
contempt with which these ushers were regarded to declare that the
father was a slave of Elpias,[222] “wearing big fetters and a collar,”
and the son was employed in “grinding the ink and sponging the
forms and sweeping out the schoolroom (παιδαγωγεῖον), the work of
a servant, not of a free boy.”
No doubt letters and music were often taught at the same school,
in different rooms. Such an arrangement would be natural and
convenient. The vases suggest it, but their evidence is uncertain.
The school buildings seem often to have been surrounded by
playgrounds. A passage in Aelian[223] shows us the boys, just let out
of school, playing at tug-of-war. No doubt in these places they
played with their hoops and tops, and amused themselves with pick-
a-back and the stone- and dice-games which corresponded to our
marbles. In villages these playgrounds probably did duty as
palaistrai.
The headmaster of the school sat on a chair with a high back;
under-masters and boys had stools without backs, but cushions were
provided. For lessons in class there were benches.[224] There was a
high reading-desk for recitations. Round the walls hung writing-
tablets, rulers, and baskets or cases containing manuscript rolls
labelled with the author’s name, composing the school library; the
rolls might also hang by themselves.[225] Masters were expected to
possess at any rate a copy of Homer—Alkibiades thrashed one who
did not. Sometimes they emended their edition themselves.[226] In
the music-schools hung lyres and flutes and flute-cases. The
(παιδαγωγειον) mentioned by Demosthenes may have been an
anteroom where the paidagogoi sat, but more probably the word is
only a rhetorical variant for “schoolroom.” There were often busts of
the Muses round the walls,[227] which were also decorated with
vases, serving for domestic purposes, and, perhaps, illustrating with
their pictures the books which the boys were reading. At a later
date, at any rate, a series of cartoons, illustrating scenes in the Iliad
and Odyssey, were sometimes hung upon the walls: the “Tabula
Iliaca,” now in the Capitoline Museum, has been recognised as a
fragment of such a series.
The first stage was to learn to read and write. Instead of a slate,
boys in Hellas had tablets of wax, usually made in two halves, so as
to fold on a hinge in the middle, the waxen surfaces coming inwards
and so being protected. Sometimes there were three pieces, forming
a triptych, or even more. For pencil, they had an instrument with a
sharp point at one end, suitable for making marks on the wax, and a
flat surface at the other, which was used to erase what had been
written, and so make the tablets ready for future use. These tablets
are shown in the school-scenes on the fifth-century vases.[228] At a
later period, when parchment and papyrus became more common,
these materials were used in the schools. Lines could be ruled with a
lump of lead, and writing done either with ink and a reed pen or
with lead; for erasures a sponge was employed.
The early stages of learning to write are described in the
Protagoras of Plato.[229] “When a boy is not yet clever at writing, the
masters first draw lines, and then give him the tablet and make him
write as the lines direct.” The passage has been variously
interpreted. Some regard the master as merely writing a series of
letters which the boy is to copy underneath. The word used in Greek
for the master’s writing is ὑπογράψαντες, and it is significant that
the word for a “copy” in this sense is a derivative of this word,
ὑπογραμμός. Such a copy, corresponding to the phrases like
“England exports engines” or “Germany grows grapes,” which are
employed in English schools for this purpose, is extant.[230] It is a
nonsense sentence designed to contain all the letters of the alphabet
μάρπτε σφὶγξ κλὼψ ζβυχθηδόν. If this rendering is correct, the
master wrote a sentence of this sort on the tablets, and the boy
copied it underneath. Others interpret the lines which the master
draws on the tablet as parallel straight lines, within which the boy
had to write. Just such a device is often employed in English copy-
books. The word used for “lines,” γραμμαί, usually means “straight
lines,” which supports this interpretation. But ὑπογραφή, on the
other hand, a derivative of ὑπογράφειν, is used for irregular traces,
e.g. a footstep,[231] and ὑπογράφειν itself is a technical term in
Hellenic art for “sketching in” what is afterwards to be finished in
detail. Consequently a third rendering of the passage makes the
master draw a faint, rough outline of the various letters, and the boy
has to go over them with his pen, marking the grooves in the wax
deeper and filling in the details. For example, in England, the master
might draw |·| and the boy go over the two vertical lines and draw
in the other two, M. Thus all three interpretations are sensible and
rest on good authority. But surely the master may be regarded as
adopting all three processes, according to the intelligence of the
pupils. For the beginner he would outline the whole letter, and leave
him only the task of going over it again. Then he would gradually
give less and less help, till the boy was capable of writing the letters
with the assistance of the parallel lines alone. Finally these would be
withdrawn, and the boy would be left to write his imitation of the
copy without assistance. The phrase in Plato is purposely vague, and
will include the whole of this process.
The letters were written in lines horizontal and vertical, so that
they fell beneath one another. No stops or accents were inserted,
and no spaces were left between words. The writing-master
probably ruled both the horizontal and the vertical lines on the tablet
for his pupil. On the Vase of Douris,[232] an under-master is
represented as writing with his pen on a wax tablet, while a boy
stands in front of him. He is probably meant either to be writing a
copy or else correcting his pupil’s exercise. Over his head hangs a
ruler, for marking out the guiding lines on the tablet. Behind the boy
sits a bearded man with a staff, who is probably the paidagogos.
The boys in the class are clearly coming up one by one to receive
their copies or have their exercises corrected, while the rest are
doing their writing. It will be noticed that there is no desk or table:
the Hellenes wrote with their tablets on their knees.
As soon as the boy had acquired a certain facility in writing, he
entered the dictation class. The master read out something, and the
boys wrote it down.[233] At first, of course, very simple words would
be dictated, and there would not be much to write. But, later on, the
boys would write at his dictation passages of the poets and other
authors. For this purpose, ink and parchment may sometimes have
been employed: Aischines seems to have “ground ink”[234] for a
writing-school. Various “elaborations in the way of speed and
beauty” of writing seem to have been customary in the case of more
advanced pupils.[235] Possibly they learnt to make flourishes and
ornamental letters. Speed would naturally be taught, for it was usual
to take notes at the lectures of Sophists and Philosophers, and
speed is required for this purpose. This must have involved the use
of the cursive letters, which otherwise were not needed, for the
Hellene had not very much writing to do, unless he became a clerk
to a public body.
Learning to read must have been a difficult business in Hellas, for
books were written in capitals at this time. There were no spaces
between the words, and no stops were inserted. Thus, the reader
had to exercise much ingenuity before he could arrive at the
meaning of a sentence. Still more difficult for the boys to grasp was
the Attic accent, upon which the masters set a great importance. So
difficult was it, that few foreigners ever acquired it, and a born
Athenian, if he went abroad for a few years, often lost the power of
speaking with the Attic intonation. The first step in learning to read
is to acquire the alphabet. The Hellenes, wishing, as usual, to make
learning as easy as possible, seem to have put the alphabet into
verse. A metrical alphabet, ascribed to Kallias, a contemporary of
Perikles, is still extant, but in a mutilated form, which has been
restored in several not very convincing ways. Probably it has been
adapted to suit different alphabets, for there were several current in
different parts of Hellas. The following is a conjectural restoration:—

ἔστ’ ἄλφα, βῆτα, γάμμα, δέλτα τ’, εἶ τε, καί


ζῆτ’, ἦτα, θῆτ’, ἴωτα, κάππα, λάβδα, μῦ,
νῦ, ξεῖ, τὸ οὖ, πεῖ, ῥῶ, τὸ σίγμα, ταῦ, τὸ ὖ,
πάροντα φεῖ τε χεῖ τε τῷ ψεῖ εἰς τὸ ὦ.[236]

This complete alphabet of twenty-four letters, which appears in


modern Greek Grammars, was not adopted for official purposes at
Athens till 403 B.C., “but it is clear that it was in ordinary use at
Athens considerably earlier.”[237]
This metrical alphabet formed the prologue to what may be called
a spelling-drama, in which the whole process of learning to spell was
expressed either in iambic lines or in choral songs. Since its author,
Kallias, is coupled with Strattis, the comic poet,[238] it may be inferred
that the play was a comedy, not a tragedy; the chorus would then
be twenty-four in number. Each member of the chorus represented
one of the twenty-four letters. In the first choric song the letters
were put together in pairs, in the fashion of a spelling class. The first
strophé runs as follows:—
Beta Alpha BA
Beta Ei BĔ
Beta Eta BĒ
Beta Iota BI
Beta Ou BŎ
Beta U BU
Beta O BŌ[239]
In the corresponding antistrophé Gamma was similarly coupled with
the seven vowels, and so on apparently through the alphabet.
During the song, which was set to excellent music, the members of
the chorus, dressed to represent the letters quite clearly, and no
doubt posturing in the right attitude, would form themselves into the
required pairs. Thus, during the first line Beta and Alpha would come
together, during the second Beta and Ei, and so on. After this song
came a lecture on the vowels, in iambic verse, the chorus being told
to repeat them one by one after the speaker. There seems to have
been a plot of some sort in this extraordinary drama, but the main
interest was, no doubt, the spelling. Opportunities were also taken
for describing the shapes of the letters, the audience having to
guess what letter was intended. This kind of alphabetical puzzle
seems to have caught the popular fancy at Athens, for Euripides,
Agathon, and Theodektes all employed it. In each case the
concealed word was “Theseus.”
Euripides’ description, if it be his, may be rendered thus:—

First, such a circle as is measured out


By compasses, a clear mark in the midst.
The second letter is two upright lines,
Another joining them across their middles.
The third is like a curl of hair. The fourth,
One upright line and three crosswise infixed.
The fifth is hard to tell: from several points
Two lines run down to form one pedestal.
The last is with the third identical.

In the same spirit, Sophocles, in his satyric drama Amphiaraos,


introduced an actor who represented the shapes of the letters by his
dancing.[240] Periclean Athens seems to have taken a very keen
interest in matters of spelling: the audience must all have known
their letters, or such devices could never have become so popular.
Kallias’ play is the ancestor of such books as Reading without
Tears. His dramatic presentation of the process of spelling must have
caught the imagination and impressed the memory of many
Athenian boys. It may even be suspected that his method was
adopted in enterprising schools, and spelling lessons were conducted
to a tune, perhaps even accompanied by dancing.[241] The tunes of
Kallias were highly praised, and were, no doubt, very different from
the monotonous drone which announces to the outside world the
presence of a Board School.
To return to more prosaic methods. Plato gives an interesting
sketch[242] of a reading class. “When boys have just learnt their
letters, they recognise any of them readily enough in the shortest
and easiest syllables, and are able to give a correct answer about
them. But in the longer and more difficult syllables they are not
certain, but form a wrong opinion and answer wrongly. Then the
best way is to take them back to the syllables in which they
recognise the same letters and then compare them with those in
which they made mistakes, and, putting them side by side, show
that in both combinations the same letters have the same meaning.”
Take an English example. The master writes scrape on the
blackboard and asks the boys to tell him what letters it contains. The
class fail to recognise the letters: the word is too long and difficult.
The master then writes beside it consecutively ape, rape, cape, in all of
which the boys recognise the letters correctly. Then crape and scrap.
From these he passes on to scrape, which they now recognise by
analogy from the words which they know already. “Finally, they learn
always to give the same name to the same letter whenever it
comes.”[243]
The methods by which boys learn to spell are the same in all
ages. “When boys come together to learn their letters, they are
asked what letters there are in some word or other.”[244] A certain
amount of mental arithmetic seems to have been included in this
stage of spelling: the pupils were asked how many letters there were
in a word, as well as the order in which they were arranged.[245] But
this will be discussed later.
While the boys were still unable to read, and often afterwards
owing to the comparative scarcity of books, the master dictated to
them the poetry which he intended them to learn by heart, and they
repeated it after him.
The Kulix of Douris gives an interesting picture of either a reading
or a repetition lesson.[246] On a high-backed chair sits an elderly
master, holding a roll in his hand. On it is inscribed what is clearly
meant to be an hexameter line from some epic poet, but Douris was
not very well educated, and so the line is misspelt and will not scan.
In front of the master stands a boy, behind whom sits an elderly
man who is probably, as in the writing scene, a paidagogos. The
master may be dictating the poem while the boy learns it by heart
after him, or he may be hearing him say it. But very possibly the
scene represents a reading-lesson. The attitudes of boy and master
are not very convenient, if both are reading out of the same book;
but this was unavoidable, for, owing to the canons of vase-painting,
the figures could only be full-faced or in profile, and the front of the
manuscript had to be turned in such a way as to be legible.
On the walls of the school hang a manuscript rolled up and tied
with a string, and an ornamental basket. These baskets were used
as bookcases, to hold the manuscript rolls. They may sometimes be
seen on vases suspended over the heads of reading figures, as in
the British Museum vase,[247] which represents a woman reading a
scroll. The paidagogos, we may notice, is revealing his humble origin
by crossing his feet, a serious offence against good manners in
Hellas.
“When the boys knew their letters and were beginning to
understand what was written, the masters put beside them on the
benches the works of good poets for them to read, and made them
learn them by heart. They chose for this purpose poets that
contained many moral precepts, and narratives and praises of the
heroes of old, in order that the boy might admire them and imitate
them and desire to become such a man himself.”[248] It is noteworthy
that Hellenic boys began at once with the very best literature to be
found in their language: there was no preliminary course of childish
tales. Grammar, when invented, was taught at a later stage: the
boys plunged straight into literature.
The schoolmasters at Athens differed as to which was the best
way of introducing boys to their national literature. The great
majority held that a properly educated boy ought to be saturated in
all poetry, comic and serious, hearing much of it in the reading class,
and learning much of it—in fact, whole poets—by heart.[249] A
minority would pick out the leading passages,[250] the “purple
patches,” and certain whole speeches,[251] and put them together
and have them committed to memory. Plato argued in favour of
expurgated editions of passages carefully selected according to a
very strict standard, since much in literature was good and much
bad.[252]
Homer, of course, played the largest part in these literary studies;
from early times “he was given an honourable place in the teaching
of the young.”[253] Vast quantities of the Iliad and Odyssey were
learnt by heart. Nikeratos, in Xenophon,[254] says: “My father, wishing
me to grow up into a good man, made me learn all the lines of
Homer; and now I can repeat the whole of the Iliad and Odyssey
from memory.” Such prodigious feats were, no doubt, assisted by the
rhapsodes, who could be heard at Athens declaiming Homer “nearly
every day.”[255] The Hellenes did not let their greatest poet lie
neglected, to be “revived” at long intervals. Homer was supposed to
teach everything, especially soldiering and good morals. “I suppose
you know,” continues Nikeratos,[256] “that Homer, the wisest of men,
has written about all human matters. So whoever of you wishes to
excel as a householder or public speaker or general, or desires to
become like Achilles or Aias or Nestor or Odusseus, let him come to
me.” Then he proceeds to show how, for example, the poet gives full
directions about the proper way to drive a chariot in a race.
Aristophanes[257] makes the shade of Aeschylus say, “Whence did
divine Homer win his honour and renown, save from this, that he
taught drill, courage, the arming of troops? Many a man of valour he
trained, and our own dead hero, Lamachos. I took my print from
him, and represented many deeds of valour done by a Patroklos or
lion-hearted Teukros, to rouse my countrymen to model themselves
upon such men, when they heard the trumpet sound.”
The great poet does not seem to have been taught pedantically;
the attention of the boys was not concentrated simply on the
difficulties of the Homeric vocabulary. In fact, probably they were
little troubled with such points; the sense, the rhythm, and the
beauty of the original do not depend upon an exact understanding of
every word, as many a modern reader has discovered. In a fragment
of Aristophanes,[258] a father asks his son the meaning of some hard
words in Homer, such as ἀμένηνα κάρηνα and κόρυμβα; the son is
quite unable to translate them, at any rate when separated from
their context, and can only retort by asking his father to interpret
some archaic phrases in Solon’s laws. A later comic poet[259]
introduced a cook who insisted on using Homeric language, just as a
modern chef writes his menu in French; the man who has hired him
is ludicrously unable to understand his phrases, and has to go in
search of a commentary.
Explanations and interpretations of supposed moral allegories in
Homer, and lessons drawn from a close study of his characters, were
very popular in Hellas, and no doubt figured in the schools.
If Homer occupied the first place in literary education, other
leading authors were not neglected. All the great poets were made
useful. “Orpheus taught ceremonial rites and abstinence from
bloodshed, and Mousaios medicine and oracles, and Hesiod the
tillage of land, the seasons of fruits and ploughing.”[260] Hesiod
probably served more as a theological handbook than as a manual of
agriculture; the moral precepts to Perses in the Works and Days
probably also found favour with schoolmasters. The fourth-century
comic poet Alexis gives an interesting catalogue of a school library.
[261] Besides Orpheus, Hesiod, and Homer, who have been mentioned

already, there are Epicharmos, Choirilos, the author of an epic poem


on the Persian war, and what is called vaguely “tragedy,” probably
meaning a selection from the great tragedians. We can see from
Plato’s attacks that Aeschylus and Euripides must have been
important in the schools, and we know that Athenian gentlemen
were expected to be able to recite them at dinner-parties, and must
therefore have learnt them by heart. The vague words “tragedy” and
“comedy” are similarly used of the recitations of the boys at Teos.
Various editions of moral precepts were also popular. Among these
were The Precepts of Cheiron, or Cheironeia, supposed to have been
given by the wise Centaur to his pupil Achilles and put into verse by
Hesiod; on a vase at Berlin three boys are seen reading this work
with apparent interest. The extant lines of Theognis are often
supposed to represent a school edition of the poet’s works,
containing the more improving portions. The lyric poets were taught
at the lyre-school, and I shall discuss them later.
Alexis also mentions “all sorts of prose works” in the school
library. The only one of these to which he gives a more definite
name is a cookery-book by Simos. But that is only introduced for the
sake of a joke; such a work would not, of course, figure in an
Athenian school. Aesop may have been a prose work read in
schools; it was considered the sign of an ignoramus “not to have
thumbed Aesop,” or to be able to quote him.[262] Such moral works
as Prodikos’ Choice of Herakles were probably popular in schools.
The case of Lusis in Plato suggests that some of the old nature-
philosophers may have been read. No doubt the school library varied
according to the taste of the master, and his freedom of choice may
have led to some curious selections. But on the whole prose works
very rarely figured in the elementary schools, partly because they
were usually too technical, still more because the artistic and literary
sense of the Hellenes regarded poetry, if only because of its greater
beauty and its imaginative value, as better for educational purposes
than prose.
It must be remembered that when boys recited Homer or
Aeschylus or Euripides, they acted them, delivering even the
narrative with a great deal of gesture, and dramatising the speeches
as fully as they could. The almost daily recitations of the rhapsodes,
and the frequent dramatic performances in the theatres, gave them
plenty of examples of the way to act. The Hellenes were extremely
sensitive and sympathetic: they were a nation of actors. The
rhapsode Ion tells Plato that, when he recited Homer, his eyes
watered and his hair stood on end. This may give the modern reader
some idea of what his repetition-lesson meant to a boy at Athens.
More may be gathered from Plato’s vehement denunciations of
dramatisation in poetry intended for use in schools; he believed that
this continuous acting exerted an evil influence upon character. But
this question will be discussed elsewhere.
The schoolrooms were used as the scene of lectures, to which
grown-up men were invited; probably the lectures would be given to
the boys at a different time. The wandering teacher, Hippias of Elis,
meeting Sokrates one day, invited him to such a lecture, which, from
its subject, was clearly meant mainly for the young.[263] After the fall
of Troy, according to the story which Hippias invented for the
occasion, Neoptolemos asked the wise old Nestor what was good
and honourable conduct and what manner of life would cause a
young man to win renown. Given this convenient opening, Nestor
replied by suggesting many excellent rules of conduct. Hippias had
delivered this lecture at Sparta, where it had won great applause. He
now proposes, he says, “to deliver it the day after to-morrow in the
schoolroom of Pheidostratos, and to impart much other valuable
information at the same time, at the request of Eudikos son of
Apemantos. Mind you come and bring any friends who will be
capable of appreciating what I say.” No doubt it was a very excellent
little sermon on the duties of life, closely analogous to Prodikos’
famous Choice of Herakles, and most improving for the pupils of
Pheidostratos, if they were allowed to attend.
One charming picture of two Athenian school friends,[264] in their
sleeveless tunics, is extant. “I saw you, Sokrates,” says a guest at a
dinner-party, “when you and Kritoboulos at the School of Letters
were both looking for something in the same book, putting your
head against his, and your bare shoulder against his shoulder.”
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