Home Programming .NET Design Patterns

.NET Design Patterns

By Praseed Pai , Shine Xavier
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    An Introduction to Patterns and Pattern Catalogs
About this book
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!
Publication date:
January 2017
Publisher
Packt
Pages
314
ISBN
9781786466150

 

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:

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.

About the Authors
  • Praseed Pai

    Praseed Pai has been working in the software industry for the last 25 years, starting his career as a MS-DOS systems programmer using ANSI C. He has been actively involved in developing large-scale, cross-platform, native code-based systems using C++ on Windows, GNU Linux, and macOS X. He has experience in COM+ and CORBA programming using C++. In the last decade, he has worked with Java- and .NET-based systems. He is the primary implementer of the SLANG4.net compilation system, which has been ported to C++ with an LLVM backend. He coauthored .NET Design Patterns, by Packt Publishing.

    Browse publications by this author
  • Shine Xavier

    Shine Xavier is a core software engineering practitioner with an extreme passion for designing/building software solutions, application frameworks, and accelerators that help maintain productivity, code quality, performance, and security. His areas of interest include functional programming, interpreters, JavaScript library development, visual programming, algorithms, performance engineering, automation, enterprise mobility, IoT and machine learning. He is currently associated with UST Global as a senior architect, where he continues to provide technical leadership in customer engagements, pre-sales, practice development, product development, innovation, and technology adoption. He lives with his wife and three kids in Thiruvananthapuram, Kerala, India.

    Browse publications by this author
Latest Reviews (4 reviews total)
Da un testo sulla programmazione ci si aspetta una certa cura nella scrittura del codice ma questo libro è orribile sia per i contenuti che per come è stato scritto: il codice non segue nessuna naming conventions per cui ci si trova con variabili scritte in tutti i modi possibili mischiate, per esempio: string archetype = ComputeArchetype(te); COMPUTATION_CONTEXT ctx = new COMPUTATION_CONTEXT(); TaxDTO td = new TaxDTO { id = te.id, taxparams = te.taxparams}; ctx.Put("tax_cargo",td); bool rs = CommandDispatcher.Dispatch(archetype, ctx); if ( rs ) { TaxDTO temp = (TaxDTO)ctx.Get("tax_cargo"); ... Inoltre si comincia subito con esempi di codice senza mai dare una definizione precisa del design pattern che si sta utilizzando (tralascio i primi 2 capitoli che sono solo un elenco di nomi di design pattern). Non provo neanche a scaricare il codice di esempio perchè mi viene male solo all'idea di leggerlo. E' il secondo libro della Packt che compro e lo trovo illeggibile credo che non ne acquisterò più in vita mia.
Le contenu c'est bon et objectif.
Simple et efficace. Que dire de plus.
.NET Design Patterns
Unlock this book and the full library FREE for 7 days
Start now