Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
.NET Design Patterns
.NET Design Patterns

.NET Design Patterns: Learn to Apply Patterns in daily development tasks under .NET Platform to take your productivity to new heights.

eBook
€17.99 €26.99
Paperback
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

.NET Design Patterns

Chapter 1. An Introduction to Patterns and Pattern Catalogs

Design patterns have always fascinated software developers, yet true knowledge of their applicability and consequences has eluded many. The various solutions that have been created and applied to solve similar problems have been studied over time by experienced developers and architects. A movement slowly began to catalog such time-tested and successful solutions, which served as a blueprint for software design. The applicability of design patterns exhibited maturity (even though over-engineering was a perceived risk) in solution architecture (in terms of stability, consistency, maintainability, and extensibility), and became a core skill for serious developers and architects. In this introduction to patterns and pattern catalogs, the authors wish to provide a detailed illustration of the movement in the software development industry that led to the discovery and consolidation of the various patterns and pattern catalogs. It is equally important to understand the evolution of patterns, idioms, programming languages, and standards that led to standardization of these technology-agnostic blueprints, which form the basis of enterprise application development today. We will cover the following topics in this regard:

  • History of object-oriented programming (OOP) techniques, idioms, and patterns
  • Patterns and pattern movement
  • Key patterns and pattern catalogs
  • Key C# language features that facilitate implementation of OOP techniques, idioms, and patterns

OOP - A short history

OOP is a programming model that is supposed to combine structure (data) and behavior (methods) to deliver software functionality. This was a marked contrast from the procedural programming model, which was mostly in vogue when the OOP model gained prominence. The primary unit of composition in a procedural programming model is a procedure (mostly a function with side-effects). Data is fed into a series of procedures that constitutes the process or algorithm in a solution context. In the case of OOP, the data and related functions are represented together as a class, which acts as a fundamental unit in the programming model. Schematically it is as follows:

    Class Test 
    { 
      <------ Static (Class Level) Variables ---------------> 
      <------ Instance (Object Level) Variables ------------> 
      <------ Private Methods ------------------------------> 
      <------ Public Methods -------------------------------> 
    } 

As a programmer, one can create many instances of a class during the execution of a program. Since class encapsulates data and its associated operations to provide a coherent entity, the problems (or rather side-effects) associated with global variables/data (being used as payload for the procedures) went away all of a sudden. This helped to manage the complexity of developing large software.

OOP revolutionized the way programmers modeled the problem domain, with class compositions leveraging encapsulation, association, inheritance, and polymorphism. Additionally, with the flexibility to model hierarchies (that closely represent the problem domain) with ease, it became natural for developers to think in terms of objects.

Note

The origin of OOP can be traced back to the Simula programming language created by Kristen Nygaard and Ole-Johan Dahl, released in the year 1965. The advent of the Smalltalk system helped the ideas of OOP to percolate to the academia and some consulting circles. Smalltalk was a dynamically typed language, and primarily designed as a message passing system. Later, they added Simula's class-based Object model. Alan Kay, Dan Inaglis, and Adele Goldberg at Xerox PARC designed the language.

The OOP model reached a critical mass in the early 1990s, with the popularity of the C++ programming language. Even though Smalltalk and C++ were OOP languages, Smalltalk was a dynamically typed programming language, and C++ was a statically typed (though weakly enforced) programming language. The C++ programming language was created by Bjarne Stroustrup at the AT&T Bell Laboratories, as an extension of C (for wider adoption). In this regard, C++, as a programming language, has issues in terms of usage because of the compulsion to make it C-compatible. The story of evolution of the language is well chronicled in, The Design and Evolution of C++, a book written by Bjarne himself. The book deals with the rationale of designing the language and the design choices available for him to incorporate features such as single inheritance, multiple inheritance, virtual methods, exception handling, templates (Generics), I/O streams, and so on. Any serious C++ developer should not miss this particular book, as it helps to understand the reason why the C++ programming language is the way it is!

There were attempts to make protocol-based development using middleware technologies like Microsoft's Component Object Model (COM) and OMG's Common Object Request Broker Architecture (CORBA). Both CORBA and COM were very similar, and both facilitated object interoperability at the binary level. Each protocol had its own binary encoding format, and interoperability between these two standards became a problem. Some enterprising companies made a living by writing COM/CORBA bridge to rectify this problem. Also, COM was mostly available only on Microsoft Windows, making it a platform-specific solution.

Then, in 1996, Sun Microsystems came up with a language which was marketed as a programming language to write applications that are hosted in a browser (Applets). They named it Java. However, due to performance and political reasons, applet development did not took off. The language, along with its associated platform, was soon projected as a server-side programming system. This was a tremendous success, and the Java language made a strong comeback, further popularizing the OOP programming model. The primary architect of the Java language was James Gosling.

In the year 2001, Microsoft released C#, a brand new OOP language for their new virtual machine development platform, known as .NET. Later, Microsoft did add support for generics, lambda, dynamic typing, and LINQ, among others, to make C# one of the most powerful programming languages in the world. The primary architect of the language was Anders Hejlsberg.

Meanwhile, languages such as Ruby and Python made an appearance, and are still relevant in certain areas. Then, there were object-functional languages such as F#, Scala, Groovy, Clojure, and so on. However, the OOP model is symbolized by C++, C#, and Java.

Patterns and pattern movement

Programmers of the early 1990s struggled a lot to understand OOP, and how to effectively use them in large projects. Without a viral medium such as the Internet, it was quite a struggle for them. Early adopters published technical reports, wrote in periodicals/journals, and conducted seminars to popularize OOP techniques. Magazines such as Dr. Dobbs Journal and C++ Report carried columns featuring OOP.

A need was felt to transfer the wisdom of the experts to the ever-increasing programming community, but this knowledge propagation was not happening. The legendary German mathematician Carl Friedrich Gauss once remarked, "Always learn from the masters". Even though Gauss had mathematics in mind, it is true for any non-trivial human endeavor. However, there were very few masters of the OOP techniques, and the apprenticeship model was not scaling well.

Note

James Coplien published an influential book titled Advanced C++ Programming Styles and Idioms, which dealt with low-level patterns (idioms) associated with the usage of the C++ programming language. Despite being not widely cited, authors consider this a notable book towards cataloguing the best practices and techniques of OOP.

  • It was during this time that Erich Gamma began his work on a pattern catalog as part of his PhD thesis, inspired by an architect named Christopher Alexander. Christopher Alexander's A Pattern Language - Towns, Buildings, Construction was a source of inspiration for Erich Gamma. Then, people with similar ideas, namely Ralph Johnson, John Vlissides, and Richard Helm, joined hands with Erich Gamma to create a catalog of 23 patterns, now popularly known as the Gang of Four (GoF) design patterns. Addison Wesley published the book Design Patterns: Elements of Reusable Object-Oriented Software in the year 1994. This soon became a great reference for the programmer, and fueled software development based on patterns. The GoF catalog was mostly focused on software design.
  • In the year 1996, a group of engineers from Siemens published a book titled Pattern-Oriented Software Architecture, which focused mostly on the architectural aspects of building a system. The entire Pattern-Oriented Software Architecture (POSA) pattern catalog was documented in five books published by John Wiley and Sons. The group was joined by Douglas Schmidt, the creator of the Adaptive Communication Environment (ACE) network programming library and TAO (The ACE ORB). He later became the chair of Object Management Group (OMG), which develops, adopts, and maintains standards such as CORBA and UML.
  • Another influential catalog was published by Martin Fowler in a book titled Patterns of Enterprise Application Architecture in the year 2001. The book mostly focused on patterns that come up while developing enterprise applications using the JEE and .NET frameworks. Incidentally, most of the code snippets were in Java and C#.
  • Gregor Hohpe and Bobby Woolf published a pattern catalog to document the patterns that arise in the enterprise integration scenario. Their catalog titled Enterprise Integration Patterns, published as part of the Martin Fowler signature book series, is widely recognized as a source of ideas regarding enterprise integration techniques. The Apache Camel integration library is inspired by this book.
  • Core J2EE Patterns: Best Practices and Design Strategies (by Deepak Alur et al.), although a platform-specific catalog, is a rich source of ideas regarding the structuring of an enterprise application. The book includes patterns for presentation, data, and service tiers in web application development.
  • Domain-Driven Design, published by Eric Evans in the year 2003, deals with a technique called domain-driven design (DDD). The book uses GoF and Patterns of Enterprise Application Architecture (POEAA) patterns to put forward a design methodology that focuses on building a persistent ignorant domain model. The book also introduces some patterns and idioms for structuring domain logic.
  • Jim Arlow and Ila Nuestadt published a book entitled Enterprise Patterns and MDA, which catalogued a set of patterns based on the Jungian Archetypes. This catalog contains nine top-level archetypes and 168 business archetypes for developing applications.

The following figure illustrates the evolution of design methodologies, programming languages, and pattern catalogs:

Patterns and pattern movement

Key pattern catalogs

Patterns are most often catalogued in some kind of pattern repository. Some of them are published as books. The most popular and widely used pattern catalog is GoF, named after the four collaborators that produced them. They are Eric Gama, Ralph Johnson, John Vlissides, and Richard Helm.

GoF patterns

The GoF catalog, named after the four creators of the catalog, started the pattern movement. The creators mostly focused on designing and architecting object-oriented software. The ideas of Christopher Alexander were borrowed to the software engineering discipline, and applied to application architecture, concurrency, security, and so on. The GoF divided the catalog into structural, creational, and behavioral patterns. The original book used C++ and Smalltalk to explain the concepts. These patterns have been ported and leveraged in most of the programming languages that exist today.

Sr. no

Pattern type

Patterns

1

Creational patterns

Abstract factory, builder, factory method, prototype, singleton.

2

Structural patterns

Adapter, bridge, composite, decorator, facade, flyweight, proxy.

3

Behavioral patterns

Chain of responsibility, command, interpreter, iterator, mediator, memento, observer, state, strategy, template method, visitor.

We believe that a good understanding of the GoF patterns is necessary for any programmer. These patterns occur everywhere, regardless of the application domain. GoF patterns help us to communicate and reason about systems in a language-agnostic manner. They are widely implemented in the .NET and Java world.

POSA catalog

POSA Volume 5 is an influential book series, which covers most of the applicable patterns while developing mission-critical systems. An element of bias is seen towards native code programming; perhaps C++ was the prevalent OOP language during the time of research. The catalog, which spanned five published volumes, is listed as follows:

Sr. no

Pattern type

Patterns

1

Architectural

Layers, pipes and filters, blackboard, broker, MVC, presentation-abstraction-control, microkernel, reflection.

2

Design

Whole-part, mater-slave, proxy, command processor, view handler, forwarder-receiver, client-dispatcher-server, publisher-subscriber.

3

Service access and configuration patterns

Wrapper façade, component configurator, interceptor, extension interface.

4

Event handling patterns

Reactor, proactor, asynchronous completion token, acceptor-connector.

5

Synchronization patterns

Scoped locking, strategized locking, thread-safe interface, double-checked locking optimization.

6

Concurrency patterns

Active object, monitor object, half-sync/half-async, leader/followers, thread-specific storage.

7

Resource acquisition patterns

Lookup, lazy acquisition, eager acquisition, partial acquisition.

8

Resource lifecycle

Caching, pooling, coordinator, resource lifecycle manager.

9

Resource release patterns

Leasing, evictor.

10

A pattern language for distributive computing

Consolidation of patterns from different catalogs in the context of distributed programming.

11

On patterns and pattern languages

This last volume gives some meta information about patterns, pattern languages, and their usage.

We believe the POSA catalog is very important (to the extent, one of the author feels, that if someone has not heard about the POSA catalog, he or she does not understand patterns) if one is writing middleware servers and scalable web infrastructure. For some reason, it has not got the kind of traction that it deserves. They are very useful for writing server-class software infrastructure such as web containers, application containers, and other middleware components.

POEAA catalog

Martin Fowler, along with some co-authors, published a book entitled Patterns of Enterprise Application Architecture. The book is a treasure trove of patterns, that helps one to structure and organize the design of enterprise applications using .NET and Java. Some of Fowler's pattern has been leveraged in the context of distributed computing by POSA-Volume 4 authors.

Sr. no

Pattern type

Patterns

1

Domain logic

Transaction script, domain model, table module, service layer.

2

Data source architectural patterns

Table data gateway, row data gateway, active record, data mapper.

3

Object-relational behavioral patterns

Unit of work, identity map, lazy load.

4

Object-relational structural patterns

Identity field, foreign key mapping, association table mapping, dependent mapping, embedded value, serialized LOB, single table inheritance, class table inheritance, concrete table inheritance, inheritance mappers.

5

Object-relational metadata mapping patterns

Metadata mapping, query object, repository.

6

Web presentation patterns

Model view controller, page controller, front controller, template view, transform view, two-step view, application controller.

7

Distribution patterns

Remote facade, data transfer object.

8

Offline concurrency patterns

Optimistic offline lock, pessimistic offline lock, coarse grained lock, implicit lock.

9

Session state patterns

Client session state, server session state, database session state.

10

Base patterns

Gateway, mapper, layer supertype, separated interface, registry, value object, money, special case, plugin, service stub, record set.

The POEAA catalog is a rich source of ideas when it comes to enterprise application software development. Some of these patterns are implemented by frameworks such as Spring (including Spring.NET), Nhibernate/Entity Framework, Windows Communication Foundation (WCF), and Windows Presentation Foundation (WPF). Awareness about the POEAA catalog helps one to reason about the architecture of pretty much everything happening in the .NET platform.

EIP catalog

A modern day enterprise requires information to flow from one application to another, in real time or while offline. Since applications use different implementation technologies, we require message passing systems to transfer the data. Most often, these communications happen in an asynchronous manner. The Enterprise Integration Patterns (EIP) catalog deals with time-tested solutions by professionals, who have cut their teeth on integration issues for recurring problems.

Sr. no

Pattern type

Patterns

1

Messaging systems

Message channel, message, pipes and filters, message router, message translator, message endpoint.

2

Messaging channels

Point-to-point channel, publish-subscribe channel, datatype channel, invalid message channel, dead letter channel, guaranteed delivery, channel adapter, messaging bridge, message bus.

3

Message construction

Command message, document message, event message, request-reply, return address, correlation identifier, message sequence, message expiration, format indicator.

4

Message routing

Content-based router, message filter, dynamic router, recipient list, splitter, aggregator, resequencer, composed message processor, scatter-gather, routing slip, process manager, message broker.

5

Message transformation

Envelope wrapper, content enricher, content filter, claim check, normalizer, canonical data model.

6

Messaging endpoints

Messaging gateway, messaging mapper, transactional client, polling consumer, event-driven consumer, competing consumers, message dispatcher, selective consumer, durable subscriber, idempotent receiver, service activator.

7

System management

Control bus, detour, wire tap, message history, message store, smart proxy, test message, channel purger.

The EIP catalog is a very influential one in transferring knowledge about strategies for asynchronous messaging and point-to-point synchronous communication between applications. The Apache Camel library implements most of the commonly occurring patterns, while doing Enterprise Application Integration (EAI). The authors feel that this catalog is worth studying should one embark on a project that requires information/data flow from one system to another, including mobile device communication with backend services (MBAAS) that involves data synchronization and queuing mechanisms.

J2EE design patterns catalog

This is a catalog that captures design experience in the form of a book entitled Core J2EE Patterns: Best Practices and Design Strategies by Deepak Alur, John Crupi, and Dan Malks. The book and the associated website deals with common solutions that can be leveraged while writing enterprise web applications. Even though conceived for the J2EE platform, the patterns outlined in the catalog can be used in any context where there is a programming model similar to the J2EE platform. Fortunately, the .NET server-side model is very similar to J2EE.

Sr. no

Pattern class

Patterns

1

Business tier pattern

Business delegate, session facade, service locator, transfer object, composite entity, transfer object, assembler, value list handler, business object, application service.

2

Presentation tier patterns

Intercepting filter, front controller, composite view, view helper, service to worker, dispatcher view, context object, application controller.

3

Integration patterns

Data access object, service activator, domain store, web service broker.

The authors believe that the J2EE catalog has been used extensively in the .NET platform, especially after Microsoft released the ASP.Net MVC programming model. The catalog is a rich source of ideas to structure your enterprise web application.

DDD-based patterns

The book entitled Domain-Driven Design by Eric J. Evans, released in the year 2003, is not a book on patterns in itself. The primary goal of the book is to outline a method by which one can create persistent ignorant domain models by leveraging the ubiquitous language used by the stakeholders in a business scenario. The book contains a lot of patterns and idioms for architecture, design, and application integration, in a model-driven manner.

Sr. no

Pattern type

Patterns

1

Patterns for supple design

Intention-revealing interfaces, side-effect-free functions, assertions, conceptual contours, standalone classes, closure of operations, declarative design.

2

Patterns for domain model expression

Associations, entities (reference objects), value objects, services, modules (packages).

3

Patterns for domain model integrity

Bounded context, context map, shared kernel, anticorruption layer, open host service, published language.

4

Patterns for domain model distillation

Core domain, generic subdomains, segregated core, abstract core.

This is one of the most influential books in terms of thought leadership towards creating a methodology that goes along with the Agile development models. The ideas from this book have percolated deep into building the present day software systems.

Arlow/Nuestadt patterns

Jim Arlow and Ila Nuestadt published a book entitled Enterprise Patterns and MDA. The book is based on the concept of an archetype borrowed from the works of Carl Gustav Jung. Archetypes are primordial entities that occur time and again in the sociocultural context across cultures. Business archetypes are entities that occur in a business context (where business is a socio-economic activity). The business archetypes covered in the book include party, CRM, product, business rules, order, inventory, units, and so on. Archetypes help model the business problem, and this gives a clear indication of the expected composition and behavior of the solution. Archetypes are a powerful meme that provide direct mapping between the business and solution models, thereby avoiding mismatch during business analysis, design, and implementation. The ideas and schema from the book can be used to write better enterprise software products.

Sr. no

Pattern type

Patterns

1

Party archetype pattern

PartyIdentifier, RegisteredIdentifier, PartySignature, PartyAuthentication, address, person, ISOGender, ethnicity, BodyMetrics, PersonName, organization, company, company names, identifiers for companies, company organizational units, partnerships and sole proprietors, preferences, PartyManager.

2

Party relationship archetype pattern

PartyRole, PartyRoleType, PartyRelationshipType, responsibilities, capabilities.

3

Customer relationship management archetype pattern

Customer, CustomerCommunicationManager, customer communication, CustomerServiceCase.

4

Product archetype pattern

ProductType, ProductInstance, SerialNumber, batch, product specification, ProductCatalog, CatalogEntry, packages, PackageType, package instance, combining ProductTypes, rule-driven package specification, ProductRelationships, price, package pricing, measured products, services, ServiceType and ServiceInstance, product pleomorphs.

5

Inventory archetype pattern

The inventory archetype, ProductInventoryEntry, ServiceInventoryEntry, inventory capacity planning, inventory management, availability, reservations.

6

Order archetype pattern

The order archetype, PurchaseOrder, SalesOrder, OrderLine, PartySummaryRoleInOrder, DeliveryReceiver, ChargeLine, OrderManager, OrderEvents, order status, LifeCycleEvents, AmendEvents, AmendOrderLineEvent, AmendPartySummaryEvent, AmendTermsAndConditionsEvent, DiscountEvent, DespatchEvent, ReceiptEvent, OrderPayment, PaymentEvents, payment strategy, PurchaseOrder process, PurchaseOrder cancellation, process PurchaseOrder, SalesOrder process archetype, SalesOrder process, process SalesOrder, OrderProcess documentation.

7

Quantity archetype pattern

Quantity archetype pattern, metric, units/SystemOfUnits, SIBaseUnit, DerivedUnit, ManHour, quantity, StandardConversion/UnitConverter.

8

Money archetype pattern

Money archetype pattern, currency, locale, ISOCountryCode, ExchangeRate/CurrencyConverter, payment.

9

Rule archetype pattern

Rule archetype pattern, business rules/system rules, RuleElement, RuleContext, rule evaluation, ActivityRule, RuleSet, RuleOverride.

The authors have borrowed ideas from the book, while creating an ontology for realizing a domain-specific language (DSL) on a mobile-based healthcare application. If one is embarking on creating a DSL-based system architecture, this book can be a good starting point for rich domain models based on business archetypes.

Should we use all of these?

Pattern catalogs are available to deal with various concerns of software development, be it design, architecture, security, data, and so on. Most applications, or even frameworks, leverage only a fraction of the patterns listed earlier. Understanding the pattern catalogs and their applicability is a rich source of design ideas for any software developer. A developer should be careful to avoid the malady of so-called pattern diarrhoea.

Sr. no

Pattern catalog

Primary use-case

1

GoF patterns

These are fundamental patterns which occur time and again, regardless of the domain. These are used in a context agnostic manner.

2

POSA catalog

The areas where these patterns are relevant include concurrency management, distributed programming, middleware software, and so on.

3

POEAA catalog

Enterprise web application development using .NET and JEE platforms.

4

EIP

Application integration in modern enterprises.

5

J2EE design patterns

Writing web applications using .NET and Java.

6

DDD

In fact, this book is a framework for developing rich domain models in a persistent ignorant manner.

7

Arlow/Nuestadt

Very useful when we are writing enterprise applications, and no need to break one's head to create the database schema. Most of the entities are available here as a business archetype.

The C# language and the .NET platform

Microsoft (MS) initially placed their bets on an enterprise architecture strategy called Windows DNA, centered on the Distributed Component Object Model (DCOM). The advent and traction of the Java programming model forced Microsoft to rework their strategy, so they decided to create a virtual machine platform called .NET. The .NET platform was released in 2002, and it was monikered Microsoft's Java. The old adage imitation is the sincerest form of flattery was echoed by industry pundits. Web development is done using the ASP.Net Web Forms programming model, and desktop development is based on Windows forms. They also created a new language for the new platform, named C#. For platform interoperability, they created .NET remoting architecture, which became the gateway for communication between homogeneous systems (including CLR-managed and unmanaged) via TCP and DCOM protocols. For communication with heterogeneous systems, open standards such as SOAP and WSDL were leveraged by remoting objects, either self-hosted or hosted, within an IIS context.

In 2003, Microsoft released .NET v1.1, which fixed many of the bugs in .NET v1.0. The release of Microsoft .NET 1.1 encouraged people to bet their future on this platform. There was no application server in its offering. This led to some delay in the adoption of the platform. A code snippet in C#, which computes the average of a series of numbers through the command line, is shown as follows:

    // Chap1_01.cs 
    using System; 
    using System.Collections; 
    class Temp 
    { 
      public static void Main(String [] args) { 
      //---- accumulate command line arguments to  
      //---- to a list 
      ArrayList a = new ArrayList(); 
      for(int i=0; i< args.Length; ++i) 
        a.Add(Convert.ToDouble(args[i])); 
      //----- aggregate value to a variable (sum) 
      double sum = 0.0; 
      foreach(double at in a) 
        sum = sum + at; 
      //------------ Compute the Average 
      double ar = sum/a.Count; 
      //------------ Spit value to the console 
      //------------ Wait for a Key  
      Console.WriteLine(ar); 
      Console.Read(); 
    } 
  } 

In 2005, Microsoft added a lot of features to their platform, which included generics and anonymous delegates. With C# 2.0, we can rewrite the average computation program by using generics and anonymous delegates as follows:

    // -- Chap1_02.cs 
    using System; 
    using System.Collections; 
    using System.Collections.Generic;public delegate double    
    Del(List<double> pa); 
    class Temp 
    { 
      public static void Main(String [] args) { 
      //----- Use a Generic List (List<T> ) 
      //----- to accumulate command line arguemnts 
      List<double> a = new List<double>(); 
      for(int i=0; i< args.Length ; ++ i ) 
      a.Add(Convert.ToDouble(args[i])); 
      //--- Define a anonymous delegate and assign 
      //--- to the variable temp 
      //--- The delegate aggregates value and  
      //--- compute average 
      Del temp = delegate(List<double> pa ) { 
        double sum = 0.0; 
        foreach( double at in pa ) 
          sum = sum + at; 
        return sum/pa.Count; 
      }; 
      //---- invoke the delegate 
      //---- and wait for the key 
      Console.WriteLine(temp(a)); 
      Console.Read(); 
     } 
   } 

The release of .NET platform 3.0 overcame the shortcomings of the previous releases by introducing WCF, WPF, and Windows Workflow Foundation (WF), which coincided with the release of the Vista platform.

Microsoft released version 3.5 of the platform with some key features including LINQ, lambda, and anonymous types. They also released the C# 3.0 programming language. Using type inference and lambda expressions, the average computation program is rewritten as follows:

    //--- Chap1_03.cs 
    using System; 
    using System.Collections; 
    using System.Collections.Generic; 
    using System.Linq; 
    class Temp { 
      public static void Main(String [] args) { 
      //---- leverage type inference feature to assign 
      //---- a List<T> and accumulate values to that list 
      var a = new List<double>(); 
      for(int i=0; i< args.Length ; ++ i ) 
        a.Add(Convert.ToDouble(args[i])); 
      //----- Define a Lambda function which passes 
      //----- through the value.  
      Func<double,double> ar2 = (x => x );

      //------ use the Sum function available with List<T> 
 
      //------ to compute the average 
      var ar = a.Sum(ar2 )/a.Count; 
      //------ Spit the value to the console 
      Console.WriteLine(ar); 
      Console.Read(); 
    } 
  } 

With Visual Studio 2010, Microsoft released C# 4.0 with support for dynamic programming. The following code snippet demonstrates dynamic typing (based on DynamicObject) and ExpandoObjects. The following code snippet shows how one can create a custom object that can add arbitrary properties and methods:

    // Chap1_04.cs 
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Dynamic; 
 
    namespace TestVS 
    { 
      class DynamicClass : DynamicObject 
    { 
      //---- underlying container for storing  
      //---- Ibject memebers 
      private Dictionary<string, Object> props = 
      new Dictionary<string, object>(); 
 
      public DynamicClass() { } 
 
      //------- Retrieve value from a member 
      public override bool TryGetMember(GetMemberBinder binder,  
      out object result){ 
        string name = binder.Name.ToLower(); 
        return props.TryGetValue(name, out result); 
      } 
      public override bool TrySetMember(SetMemberBinder binder, 
      object value){ 
        props[binder.Name.ToLower()] = value; 
        return true; 
      } 
    } 
 
    class Program{ 
      static void Main(string[] args){ 
        dynamic dc = new DynamicClass(); 
        //--------- Adding a property 
        dc.hell = 10; 
        //--------read back the property... 
        Console.WriteLine(dc.hell); 
        //------- Creating an Action delegate... 
        Action<int> ts = new Action<int>( delegate(int i ) { 
          Console.WriteLine(i.ToString()); 
        }); 
        //------------Adding a method.... 
        dc.rs = ts; 
        //----------- invoking a method.... 
        dc.rs(100); 
        Console.Read(); 
      } 
    } 
  } 

The following code snippet shows how one can use ExpandoObject to add a property to a type we created. We will be leveraging the dynamic feature of C# 4.0:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Dynamic;  
 
    namespace TestVS 
    { 
      class Program 
    { 
      static void Main(string[] args){ 
        dynamic ds = new ExpandoObject();
      //---- Adding a property 
        ds.val = 20; 
        Console.WriteLine(ds.val); 
        //---- Assign a new value to the "val" property 
        //-----This is possible because of dynamic typing  
        ds.val = "Hello World..."; 
        Console.WriteLine(ds.val); 
        //---------------- Wait for the Keyboard input 
        Console.Read(); 
      } 
    } 
  } 

In 2012, Microsoft released version 5.0 of the C# programming language, which incorporated a declarative concurrency model based on the async/await paradigm. The following C# code demonstrates the usage of async/await:

    //-- Chap1_05.cs 
    using System; 
    using System.IO; 
    using System.Threading.Tasks; 
 
    class Program 
    { 
      static void Main() { 
        //--- Create a Task to Start processing 
        Task task = new Task(ProcessCountAsync); 
        task.Start();
    task.Wait(); 
        Console.ReadLine(); 
      } 
 
    static async void ProcessCountAsync() 
    { 
      // Start the HandleFile method. 
      Task<int> task = HandleFileAsync(@".\WordCount.txt"); 
      // 
      // -------- One can do some lengthy processing here 
      //  
      int x = await task; 
      Console.WriteLine("Count: " + x); 
    } 
 
    static async Task<int> HandleFileAsync(string file) 
    { 
      int count = 0; 
      using (StreamReader reader = new StreamReader(file)) 
      { 
        string v = await reader.ReadToEndAsync(); 
        count += v.Length; 
      } 
      return count; 
    } 
  } 

With Visual Studio 2015, Microsoft released C# 6.0, which mostly contains cosmetic changes to the language. Additionally, C# 7.0 does not add many features to the language. The .NET Core released by Microsoft runs on Windows GNU Linux and MAC OS X, promises to make C# a multiplatform/cross platform language. The acquisition of Xamarin has helped Microsoft to foray into cross-platform, native code-based mobile development.

C# language and the singleton pattern

The authors consider the singleton pattern, the way it was presented in the GoF book, as some kind of anti-pattern. A lot has been written about how to implement it in a multi-core/multi-threaded environment. Constructs such as the double-checked locking pattern have been implemented to incorporate lazy loading while implementing singleton.

The C# programming language has got a nifty feature called a static constructor, which helps to implement the singleton pattern in a thread-safe manner. The static constructor is guaranteed to be called before any method (including the constructor) is called. We believe we can stop cutting down trees in order to write about the singleton pattern, at least in the .NET world.

    //--Chap1_06.cs 
    using System; 
 
    class SingleInstance 
    { 
      private int value = 10; 
      //----- In the case of Singleton Pattern, we make our 
      //----- ctor private to avoid instantiating the object using 
      //----- the new keyword 
      private SingleInstance() { } 
 
      //----- The static method acts as a mechanism to expose 
      //------ the internal instance 
      public static SingleInstance Instance {  
        get {  
          return Nested.instance; 
        }  
      } 
 
      private class Nested 
      { 
        static Nested() { } 
        internal static readonly SingleInstance instance 
        = new SingleInstance(); 
      } 
      public void Increment() 
      { 
        value++; 
      } 
      public int Value { get { return value; } } 
    } 
 
    public class SingletonExample 
    { 
      public static void Main(String[] args) 
    { 
      SingleInstance t1 = SingleInstance.Instance; 
      SingleInstance t2 = SingleInstance.Instance; 
      t1.Increment(); 
      if (t1.Value == t2.Value) 
        Console.WriteLine("SingleTon Object"); 
    } 
  } 

Summary

The pattern movement has revolutionized the way people are developing software. By capturing the wisdom of experts in their respective areas, pattern catalogs can be used for software engineering, library design, and all areas where they are available. The famous GoF pattern book started the whole movement in the year 1994. Some notable catalogs include POSA, POEAA, EIP, J2EE, DDD, and Arlow/Nuestadt. We have also seen how a multi-paradigm language such as C# is well-suited for pattern-based software development, considering the language's evolution in terms of features. We will continue to explore the applicability and consequence of patterns in the following chapters. We will also be looking at the key design principles, and will explain the need for design patterns using an application case study.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Dive into the powerful fundamentals of .NET framework for software development
  • • The code is explained piece by piece and the application of the pattern is also showcased.
  • • This fast-paced guide shows you how to implement the patterns into your existing applications

Description

Knowing about design patterns enables developers to improve their code base, promoting code reuse and making their design more robust. This book focuses on the practical aspects of programming in .NET. You will learn about some of the relevant design patterns (and their application) that are most widely used. We start with classic object-oriented programming (OOP) techniques, evaluate parallel programming and concurrency models, enhance implementations by mixing OOP and functional programming, and finally to the reactive programming model where functional programming and OOP are used in synergy to write better code. Throughout this book, we’ll show you how to deal with architecture/design techniques, GoF patterns, relevant patterns from other catalogs, functional programming, and reactive programming techniques. After reading this book, you will be able to convincingly leverage these design patterns (factory pattern, builder pattern, prototype pattern, adapter pattern, facade pattern, decorator pattern, observer pattern and so on) for your programs. You will also be able to write fluid functional code in .NET that would leverage concurrency and parallelism!

Who is this book for?

This book is for those with familiarity with .NET development who would like to take their skills to the next level and be in the driver’s seat when it comes to modern development techniques. Basic object-oriented C# programming experience and an elementary familiarity with the .NET framework library is required.

What you will learn

  • • Put patterns and pattern catalogs into the right perspective
  • • Apply patterns for software development under C#/.NET
  • • Use GoF and other patterns in real-life development scenarios
  • • Be able to enrich your design vocabulary and well articulate your
  • design thoughts
  • • Leverage object/functional programming by mixing OOP and FP
  • • Understand the reactive programming model using Rx and RxJs
  • • Writing compositional code using C# LINQ constructs
  • • Be able to implement concurrent/parallel programming techniques
  • using idioms under .NET
  • • Avoiding pitfalls when creating compositional, readable, and
  • maintainable code using imperative, functional, and reactive code.
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 31, 2017
Length: 314 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466150
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Austria

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Jan 31, 2017
Length: 314 pages
Edition : 1st
Language : English
ISBN-13 : 9781786466150
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 116.97
Enterprise Application Architecture with .NET Core
€41.99
C# 7 and .NET Core Cookbook
€41.99
.NET Design Patterns
€32.99
Total 116.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. An Introduction to Patterns and Pattern Catalogs Chevron down icon Chevron up icon
2. Why We Need Design Patterns? Chevron down icon Chevron up icon
3. A Logging Library Chevron down icon Chevron up icon
4. Targeting Multiple Databases Chevron down icon Chevron up icon
5. Producing Tabular Reports Chevron down icon Chevron up icon
6. Plotting Mathematical Expressions Chevron down icon Chevron up icon
7. Patterns in the .NET Base Class Library Chevron down icon Chevron up icon
8. Concurrent and Parallel Programming under .NET Chevron down icon Chevron up icon
9. Functional Programming Techniques for Better State Management Chevron down icon Chevron up icon
10. Pattern Implementation Using Object/Functional Programming Chevron down icon Chevron up icon
11. What is Reactive Programming? Chevron down icon Chevron up icon
12. Reactive Programming Using .NET Rx Extensions Chevron down icon Chevron up icon
13. Reactive Programming Using RxJS Chevron down icon Chevron up icon
14. A Road Ahead Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.6
(5 Ratings)
5 star 60%
4 star 0%
3 star 0%
2 star 20%
1 star 20%
Viby Abraham Jul 07, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Window to the broad world of patterns!
Amazon Verified review Amazon
DocTRex Jan 21, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is quite informative, and I did enjoy it, however, it feels dumbed down and of lesser quality when compared to other publishers. Firstly, it follows no code style and C# naming convention (camel case method names and such). Additionally, I discovered small inconsistencies in code, which make me feel like no attention was given (ex. "{get;set;}," "{ get; set;}," and "{ get; set; }" all in the same example). Regardless, I'm happy I bought it, and I don't want to give a poor review for minor errors.
Amazon Verified review Amazon
stathis Feb 01, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfect book
Amazon Verified review Amazon
Sreeraj N R Sep 06, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Difficult to follow for a medium level user and the book is little expensive compared to available books for the same topics in the market
Amazon Verified review Amazon
Mr M Hill Feb 28, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
This book starts out by regurgitating multiple pages of acronyms and pattern names without actually explaining anything. There was no point to these pages. The same lack of care is found throughout the book; code is poorly formatted, variables unclearly named, and comments chewing up all the whitespace. Add to this the atrocious grammar and you've got yourself a book that struggles to convey meaning. The exact opposite of what you need when dealing with the complexities of design.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela