Home > Store

C# Design Patterns: A Tutorial

Register your product to gain access to bonus material or receive a coupon.

C# Design Patterns: A Tutorial

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 2003
  • Dimensions: 7-3/8" x 9-1/4"
  • Pages: 416
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-84453-2
  • ISBN-13: 978-0-201-84453-5

This is a practical book that explains how to write C# programs using some of the most common design patterns. With the release of C# and Visual Studio .NET, there is a new interest in the Microsoft development community in some of the OO world's key tools, such as UML and Design Patterns, which they had neglected before. The book covers every pattern identified in Gamma et al's Design Patterns which can be executed in C#. For each pattern, it starts with a brief verbal description, and then builds simple example programs. Each of these examples is a visual program that can be run and examined to make the pattern as concrete a concept as possible. All of the examples will be on the companion CD. The emphasis is on the practical ways to use these patterns to ease the developer's day to day work. This book should be well timed for the growing number of developers who have learned the basics of C#, and now want information on how to get the most out of C# in their real-world application development.

Sample Content

Online Sample Chapters

C# Design Patterns: The Adapter Pattern

C# Design Patterns: The Bridge Pattern

C# Design Patterns: The Composite Pattern

C# Design Patterns: The Decorator Pattern

C# Design Patterns: The Façade Pattern

C# Design Patterns: The Flyweight Pattern

C# Design Patterns: The Proxy Pattern

Downloadable Sample Chapter

Click below for Sample Chapter(s) related to this title:
Sample Chapter 3

Sample Pages

Download the sample pages (includes Chapter 3 and Index)

Table of Contents



Preface.


Acknowledgments.

I. OBJECT-ORIENTED PROGRAMMING IN C#.

1. What Are Design Patterns?

Defining Design Patterns.

The Learning Process.

Studying Design Patterns.

Notes on Object-Oriented Approaches.

C# Design Patterns.

How This Book Is Organized.

2. Syntax of the C# Language.

Data Types.

Converting between Numbers and Strings.

Declaring Multiple Variables.

Numeric Constants.

Character Constants.

Variables.

Declaring Variables as You Use Them.

Multiple Equals Signs for Initialization.

A Simple C# Program.

Arithmetic Operators.

Increment and Decrement Operators.

Combining Arithmetic and Assignment Statements.

Making Decisions in C#.

Comparison Operators.

Combining Conditions.

The Most Common Mistake.

The Switch Statement.

C# Comments.

The Ornery Ternary Operator.

Looping Statements in C#.

The While Loop.

The Do-While Statement.

The For Loop.

Declaring Variables as Needed in For Loops.

Commas in For Loop Statements.

How C# Differs from C.

How C# Differs from Java.

Summary.

3. Writing Windows C# Programs.

Objects in C#.

Managed Languages and Garbage Collection.

Classes and Namespaces in C#.

Building a C# Application.

The Simplest Window Program in C#.

Windows Controls.

Labels.

TextBox.

CheckBox.

Buttons.

Radio Buttons.

ListBoxes and ComboBoxes.

The Items Collection.

Menus.

ToolTips.

The Windows Controls Program.

Summary.

Programs on the CD-ROM.

4. Using Classes and Objects in C#.

What Do We Use Classes For?

A Simple Temperature Conversion Program.

Building a Temperature Class.

Converting to Kelvin.

Putting the Decisions into the Temperature Class.

Using Classes for Format and Value Conversion.

Handling Unreasonable Values.

A String Tokenizer Class.

Classes as Objects.

Class Containment.

Initialization.

Classes and Properties.

Programming Style in C#.

Delegates.

Indexers.

Operator Overloading.

Summary.

Programs on the CD-ROM.

5. Inheritance.

Constructors.

Drawing and Graphics in C#.

Using Inheritance.

Namespaces.

Creating a Square from a Rectangle.

Public, Private, and Protected.

Overloading.

Virtual and Override Keywords.

Overriding Methods in Derived Classes.

Replacing Methods Using New.

Overriding Windows Controls.

Interfaces.

Abstract Classes.

Comparing Interfaces and Abstract Classes.

Summary.

Programs on the CD-ROM.

6. UML Diagrams.

Inheritance.

Interfaces.

Composition.

Annotation.

WithClass UML Diagrams.

C# Project Files.

7. Arrays, Files, and Exceptions in C#.

Arrays.

Collection Objects.

ArrayLists.

Hashtables.

SortedLists.

Exceptions.

Multiple Exceptions.

Throwing Exceptions.

File Handling.

The File Object.

Reading a Text File.

Writing a Text File.

Exceptions in File Handling.

Testing for End of File.

A csFile Class.

Program on the CD-ROM.

II. CREATIONAL PATTERNS.

8. The Simple Factory Pattern.

How a Simple Factory Works.

Sample Code.

The Two Derived Classes.

Building the Simple Factory.

Using the Factory.

Factory Patterns in Math Computation.

Summary.

Thought Questions.

Programs on the CD-ROM.

9. The Factory Method.

The Swimmer Class.

The Events Classes.

StraightSeeding.

CircleSeeding.

Our Seeding Program.

Other Factories.

When to Use a Factory Method.

Thought Question.

Program on the CD-ROM.

10. The Abstract Factory Pattern.

A GardenMaker Factory.

The PictureBox.

Handling the RadioButton and Button Events.

Adding More Classes.

Consequences of Abstract Factory.

Thought Question.

Program on the CD-ROM.

11. The Singleton Pattern.

Creating Singleton Using a Static Method.

Exceptions and Instances.

Throwing the Exception.

Creating an Instance of the Class.

Providing a Global Point of Access to a Singleton.

Other Consequences of the Singleton Pattern.

Programs on the CD-ROM.

12. The Builder Pattern.

An Investment Tracker.

The Stock Factory.

The CheckChoice Class.

The ListboxChoice Class.

Using the Items Collection in the ListBox Control.

Plotting the Data.

The Final Choice.

Consequences of the Builder Pattern.

Thought Questions.

Program on the CD-ROM.

13. The Prototype Pattern.

Cloning in C#.

Using the Prototype.

Cloning the Class.

Using the Prototype Pattern.

Dissimilar Classes with the Same Interface.

Prototype Managers.

Consequences of the Prototype Pattern.

Thought Question.

Programs on the CD-ROM.

Summary of Creational Patterns.

III. STRUCTURAL PATTERNS.

14. The Adapter Pattern.

Moving Data between Lists.

Making an Adapter.

Using the DataGrid.

Detecting Row Selection.

Using a TreeView.

The Class Adapter.

Two-Way Adapters.

Object versus Class Adapters in C#.

Pluggable Adapters.

Thought Question.

Programs on the CD-ROM.

15. The Bridge Pattern.

The Bridger Interface.

The VisList Classes.

The Class Diagram.

Extending the Bridge.

Windows Forms as Bridges.

Consequences of the Bridge Pattern.

Thought Question.

Programs on the CD-ROM.

16 The Composite Pattern.

An Implementation of a Composite.

Computing Salaries.

The Employee Classes.

The Boss Class.

Building the Employee Tree.

Self-Promotion.

Doubly Linked Lists.

Consequences of the Composite Pattern.

A Simple Composite.

Composites in .NET.

Other Implementation Issues.

Thought Questions.

Programs on the CD-ROM.

17. The Decorator Pattern.

Decorating a CoolButton.

Handling Events in a Decorator.

Layout Considerations.

Control Size and Position.

Multiple Decorators.

Nonvisual Decorators.

Decorators, Adapters, and Composites.

Consequences of the Decorator Pattern.

Thought Questions.

Programs on the CD-ROM.

18. The Facade Pattern.

What Is a Database?

Getting Data Out of Databases.

Kinds of Databases.

ODBC.

Database Structure.

Using ADO.NET.

Connecting to a Database.

Reading Data from a Database Table.

Executing a Query.

Deleting the Contents of a Table.

Adding Rows to Database Tables Using ADO.NET.

Building the Facade Classes.

Building the Price Query.

Making the ADO.NET Facade.

The DBTable Class.

Creating Classes for Each Table.

Building the Price Table.

Loading the Database Tables.

The Final Application.

What Constitutes the Facade?

Consequences of the Facade.

Thought Question.

Program on the CD-ROM.

19. The Flyweight Pattern.

Discussion.

Example Code.

The Class Diagram.

Selecting a Folder.

Handling the Mouse and Paint Events.

Flyweight Uses in C#.

Sharable Objects.

Copy-on-Write Objects.

Thought Question.

Program on the CD-ROM.

20. The Proxy Pattern.

Sample Code.

Proxies in C#.

Copy-on-Write.

Comparison with Related Patterns.

Thought Question.

Program on the CD-ROM.

Summary of Structural Patterns.

IV. BEHAVIORAL PATTERNS.

21. Chain of Responsibility.

Applicability.

Sample Code.

ListBoxes.

Programming a Help System.

Receiving the Help Command.

A Chain or a Tree?

Kinds of Requests.

Examples in C#.

The Chain of Responsibility.

Thought Question.

Programs on the CD-ROM.

22. The Command Pattern.

Motivation.

Command Objects.

Building Command Objects.

Consequences of the Command Pattern.

The CommandHolder Interface.

Providing Undo.

Thought Questions.

Programs on the CD-ROM.

23. The Interpreter Pattern.

Motivation.

Applicability.

A Simple Report Example.

Interpreting the Language.

Objects Used in Parsing.

Reducing the Parsed Stack.

Implementing the Interpreter Pattern.

The Syntax Tree.

Consequences of the Interpreter Pattern.

Thought Question.

Program on the CD-ROM.

24. The Iterator Pattern.

Motivation.

Sample Iterator Code.

Fetching an Iterator.

Filtered Iterators.

The Filtered Iterator.

Keeping Track of the Clubs.

Consequences of the Iterator Pattern.

Programs on the CD-ROM.

25. The Mediator Pattern.

An Example System.

Interactions between Controls.

Sample Code.

Initialization of the System.

Mediators and Command Objects.

Consequences of the Mediator Pattern.

Single Interface Mediators.

Implementation Issues.

Program on the CD-ROM.

26. The Memento Pattern.

Motivation.

Implementation.

Sample Code.

A Cautionary Note.

Command Objects in the User Interface.

Handling Mouse and Paint Events.

Consequences of the Memento.

Thought Question.

Program on the CD-ROM.

27. The Observer Pattern.

Watching Colors Change.

The Message to the Media.

Consequences of the Observer Pattern.

Program on the CD-ROM.

28. The State Pattern.

Sample Code.

Switching between States.

How the Mediator Interacts with the StateManager.

The ComdToolBarButton.

Handling the Fill State.

Handling the Undo List.

The VisRectangle and VisCircle Classes.

Mediators and the God Class.

Consequences of the State Pattern.

State Transitions.

Thought Questions.

Program on the CD-ROM.

29 The Strategy Pattern.

Motivation.

Sample Code.

The Context.

The Program Commands.

The Line and Bar Graph Strategies.

Drawing Plots in C#.

Making Bar Plots.

Making Line Plots.

Consequences of the Strategy Pattern.

Program on the CD-ROM.

30. The Template Method Pattern.

Motivation.

Kinds of Methods in a Template Class.

Sample Code.

Drawing a Standard Triangle.

Drawing an Isosceles Triangle.

The Triangle Drawing Program.

Templates and Callbacks.

Summary and Consequences.

Programs on the CD-ROM.

31. The Visitor Pattern.

Motivation.

When to Use the Visitor Pattern.

Sample Code.

Visiting the Classes.

Visiting Several Classes.

Bosses Are Employees, Too.

Catch-All Operations with Visitors.

Double Dispatching.

Why Are We Doing This?

Traversing a Series of Classes.

Consequences of the Visitor Pattern.

Thought Question.

Program on the CD-ROM.

Bibliography.
Index. 0201844532T08292002

Preface

This is a practical book that tells you how to write C# programs using some of the most common design patterns. It also serves as a quick introduction to programming in the new C# language. The pattern discussions are structured as a series of short chapters, each describing a design pattern and giving one or more complete working, visual example programs that use that pattern. Each chapter also includes UML diagrams illustrating how the classes interact.

This book is not a "companion" book to the well-known Design Patterns text by the "Gang of Four." Instead, it is a tutorial for people who want to learn what design patterns are about and how to use them in their work. You do not have to have read Design Patterns to read this book, but when you are done here you may well want to read or reread it to gain additional insights.

In this book, you will learn that design patterns are frequently used ways of organizing objects in your programs to make them easier to write and modify. You'll also see that by familiarizing yourself with them, you've gained some valuable vocabulary for discussing how your programs are constructed.

People come to appreciate design patterns in different ways--from the highly theoretical to the intensely practical--and when they finally see the great power of these patterns, an "Aha!" moment occurs. Usually this moment means that you suddenly have an internal picture of how that pattern can help you in your work.

In this book, we try to help you form that conceptual idea, or gestalt, by describing the pattern in as many ways as possible. The book is organized into six main sections: an introductory description, an introduction to C#, and descriptions of patterns, grouped as creational, structural, and behavioral.

For each pattern, we start with a brief verbal description and then build simple example programs. Each of these examples is a visual program that you can run and examine to make the pattern as concrete a concept as possible. All of the example programs and their variations are on the companion CD-ROM, where you run them, change them, and see how the variations you create work.

Since each of the examples consists of a number of C# files for each of the classes we use in that example, we provide a C# project file for each example and place each example in a separate subdirectory to prevent any confusion. This book assumes you have and will be using a copy of Visual Studio.NET. This product comes in several versions: we used the Professional Edition in developing the code samples.

If you leaf through the book, you'll see screen shots of the programs we developed to illustrate the design patterns, providing yet another way to reinforce your learning of these patterns. In addition, you'll see UML diagrams of these programs, illustrating the interactions between classes in yet another way. UML diagrams are just simple box and arrow illustrations of classes and their inheritance structure, where arrows point to parent classes, and dotted arrows point to interfaces. And if you're not yet familiar with UML, we provide a simple introduction in the second chapter.

When you finish this book, you'll be comfortable with the basics of design patterns and will be able to start using them in your day-to-day C# programming work.

James W. Cooper
Nantucket, MA
Wilton, CT
Kona, HI


0201844532P05132002

Index

Click below to download the Index file related to this title:
Index

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020