Monday, November 19, 2012

How to Avoid the Top Five SharePoint Performance Mistakes

Copyright from: andreasgrabner.sys-con.com


SharePoint is without question a fast-growing platform and Microsoft is making lots of money with it. It’s been around for almost a decade and grew from a small list and document management application into an application development platform on top of ASP.NET using its own API to manage content in the SharePoint Content Database.
Over the years many things have changed – but some haven’t – like – SharePoint still uses a single database table to store ALL items in any SharePoint List. And this brings me straight into the #1 problem I have seen when working with companies that implemented their own solution based on SharePoint.
#1: Iterating through SPList Items
As a developer I get access to a SPList object – either using it from my current SPContext or creating a SPList object to access a list identified by its name. SPList provides an Items property that returns a SPListItemCollection object. The following code snippet shows one way to display the Title column of the first 100 items in the current SPList object:
SPList activeList = SPContext.Current.List;
for(int i=0;i<100 activelist.items.count="activelist.items.count" amp="amp" br="br" i="i">  SPListItem listItem = activeList.Items[i];
  htmlWriter.Write(listItem["Title"]);
}
Looks good – right? Although the above code works fine and performs great in a local environment it is the number 1 performance problem I’ve seen in custom SharePoint implementations. The problem is the way the Items property is accessed. The Items property queries ALL items from the Content Database for the current SPList and “unfortunately” does that every time we access the Items property. The retrieved items ARE NOT CACHED. In the loop example we access the Items property twice for every loop iteration – once to retrieve the Count, and once to access the actual Item identified by its index. Analyzing the actual ADO.NET Database activity of that loop shows us the following interesting result:
200 SQL Statements get executed when iterating through  SPList.Items
200 SQL Statements get executed when iterating through SPList.Items
Problem: The same SQL Statement is executed all over again which retrieves ALL items from the content database for this list. In my example above I had 200 SQL calls totalling up to more than 1s in SQL Execution Time.
Solution: The solution for that problem is rather easy but unfortunately still rarely used. Simply store the SPListItemCollection object returned by the Items property in a variable and use it in your loop:
SPListItemCollection items = SPContext.Current.List.Items;
for(int i=0;i<100 amp="amp" br="br" i="i" items.count="items.count">  SPListItem listItem = items[i];
  htmlWriter.Write(listItem["Title"]);
}
This queries the database only once and we work on an in-memory collection of all retrieved items.
Further readingsThe wrong way to iterate through SharePoint SPList Items and Performance Considerations when using the SharePoint Object Model
#2: Requesting too much data from the content database
It is convenient to access data from the Content Database using the SPList object. But – every time we do so we end up requesting ALL items of the list. Look closer at the SQL Statement that is shown in the example above. It starts with SELECT TOP 2147483648 and returns all defined columns in the current SPList.
Most developers I worked with were not aware that there is an easy option to only query the data that you really need using the SPQuery object. SPQuery allows you to:
a) limit the number of returned items
b) limit the number of returned columns
c) query specific items using CAML (Collaborative Markup Language)
Limit the number of returned items
If I only want to access the first 100 items in a list – or e.g.,: page through items in steps of 100 elements (in case I implement data paging in my WebParts) I can do that by using the SPQuery RowLimit and ListItemCollectionPosition property. Check out Page through SharePoint Lists for a full example:
SPQuery query = new SPQuery();
query.RowLimit = 100; // we want to retrieve 100 items

query.ListItemCollectionPosition = prevItems.ListItemCollectionPosition; // starting at a previous positionSPListItemCollection items = SPContext.Current.List.GetItems(query);
// now iterate through the items collection
The following screenshot shows us that SharePoint actually takes the RowLimit count and uses it in the SELECT TOP clause to limit the number of rows returned. It also uses the ListItemCollectionPosition in the WHEREclause to only retrieve elements with an ID > previous position.
SPQuery.RowLimit limits the number of records retrieved from the  SharePoint Content Database
SPQuery.RowLimit limits the number of records retrieved from the SharePoint Content Database
Limit the number of returned columns
If you only need certain columns from the List SPQuery.ViewFields can be used to specify which Columns to retrieve. By default – all columns are queried which causes extra stress on the database to retrieve the data, requires more network bandwidth to transfer the data from SQL Server to SharePoint, and consumes more memory in your ASP.NET Worker Process. Here is an example of how to use the ViewFields property to only retrieve the IDText Field and XZY Column:
SPQuery query = new SPQuery();
query.ViewFields = "";
Looking at the generated SQL makes the difference to the default query mode obvious:
SELECT clause only selects those columns defined in SPView or  ViewFields
SELECT clause only selects those columns defined in SPView or ViewFields
Query specific elements using CAML
CAML allows you to be very specific in which elements you want to retrieve. The syntax is a bit “bloated” (that is my personal opinion) as it uses XML to define a SQL WHERE like clause. Here is an example of such a query:
SPQuery query = new SPQuery();
query.Query = “15”;
As I said it is a bit “bloated” but it hey – it works :-)
Problem: The main problem that I’ve seen is that developers usually go straight on and only work through SPList to retrieve list items resulting in too much data retrieved from the Content Database
Solution: Use the SPQuery object and its features to limit the number of elements and columns
Further readingsOnly request the data you really need and Page through SharePoint lists
#3: Memory Leaks with SPSite and SPWeb
In the very beginning I said “many things have changed – but some haven’t”. SharePoint still uses COM Components for some of its core features – a relict of “the ancient times”. While there is nothing wrong with COM, there is with memory management of COM Objects. SPSite and SPWeb objects are used by developers to gain access to the Content Database. What is not obvious is that these objects have to be explicitly disposed in order for the COM objects to be released from memory once no longer needed.
Problem: The problem SharePoint installations run into by not disposing SPSite and SPWeb objects is that the ASP.NET Worker Process is leaking memory (native and managed) and will end up being recycled by IIS in case we run out of memory. Recycling means losing all current user sessions and paying a performance penalty for those users that hit the worker process again after recycling is finished (first requests are slow during startup).
Solution: Monitor your memory usage to identify whether you have a memory leak or not. Use a memory profiler to identify which objects are leaking and what is creating them. In case of SPSite and SPWeb you should follow the Best Practices as described on MSDN. Microsoft also provides a tool to identify leaking SPSite and SPWeb objects called SPDisposeCheck.
The following screenshot shows the process of monitoring memory counters, using memory dumps and analyzing memory allocations using dynaTrace :
Identifying leaking SPSite and SPWeb Objects
Identifying leaking SPSite and SPWeb Objects
Further readingIdentifying memory problems introduced by custom code
#4: Index Columns are not necessarily improving performance
When I did my SharePoint research during my first SharePoint engagements I discovered several “interesting” implementation details about SharePoint. Having only a single database table to store all List Items makes it a bit tricky to propagate index column definitions down to SQL Server. Why is that? If we look at the AllUserData table in your SharePoint Content Database we see that this table really contains columns for all possible columns that you can ever have in any SharePoint list. We find for instance 64 nvarchar, 16 ints, 12 floats, …
If you define an index on the first text column in your “My SharePoint List 1” and another index column on the 2nd number column in your “My SharePoint List 2” and so on and so on you would end up having database indices defined on pretty much every column in your Content Database. Check out the further reading link to a previous blog of mine – it gives you a good overview of how the AllUserData table looks like.
Problem: Index Columns can speed up access to SharePoint Lists – but – due to the nature of the implementation of Indices in SharePoint we have the following limitations:
a) for every defined index SharePoint stores the index value for every list item in a separate table. Having a list with let’s say 10000 items means that we have 10000 rows in AllUserData and 10000 additional rows in the NameValuePair table (used for indexing)
b) queries only make use of the first index column on a table. Additional index columns are not used to speed up database access
Solution: Really think about your index columns. They definitely help in cases where you do lookups on text columns. Keep in mind the additional overhead of an index and that multiple indices don’t give you additional performance gain.
Further readingsHow list column indices really work under the hood and More on column index and their performance impact
#5: SharePoint is not a relational database for high volume transactional processing
This problem should actually be #1 on my list and here is why: In the last 2 years I’ve run into several companies that made one big mistake: they thought SharePoint is the most flexible database on earth as they could define Lists on the fly – modifying them as they needed them without worrying about the underlying database schema or without worrying to update the database access logic after every schema change. Besides this belief these companies have something else in common: They had to rewrite their SharePoint application by replacing the Content Database in most parts of their applications with a “regular” relational database.
Problem: If you read through the previous four problem points it should be obvious why SharePoint is not a relational database and why it should not be used for high-volume transactional processing. Every data element is stored in a single table. Database indices are implemented using a second table that is then joined to the main table. Concurrent access to different lists is a problem because the data comes from the same table.
Solution: Before starting a SharePoint project really think about what data you have – how frequently you need it and how many different users modify it. If you have many data items that change frequently you should really consider using your own relational database. The great thing about SharePoint is that you are not bound to the Content Database. You can practically do whatever you want including access to any external database. Be smart and don’t end up rewriting your application after you’ve invested too much time already.
Further readingMonitoring individual List usage and performance and How list column indices really work under the hood
Final words
These findings are a summary of the work I did on SharePoint in the last two years. I’ve spoken at several conferences and worked with different companies helping them to speed up their SharePoint installations. Follow the links under Further Readings in the individual paragraphs or simply check out all SharePoint related blog articles. Some of my SharePoint Conference talks have been recorded (video + screen capture) and you can watch them on the Conference Material Download page.
As SharePoint is built on the .NET Platform you might also be interested in my latest White Papers about Continuous Application Performance for Enterprise .NET Systems
Related reading:
  1. SharePoint: More on column index and their performance impact In my previous post I took a closer look into...
  2. SharePoint: List Performance – How list column indices really work under the hood Have you ever wondered what is really going on under...
  3. SharePoint: Only request data that you really need One of the main performance problems that we can witness...
  4. SharePoint: Lookup value Performance In SharePoint you can define lookup columns in your lists....
  5. SharePoint: Page through SharePoint lists SharePoint lists can contain thousands of items. We have all heard...

Wednesday, July 18, 2012

Application Middleware Design

copyright from: www.dsoftworld.com
Business Logic Layer

The business logic layer is an abstract layer that contains all the rules, workflow and validation that define and deal with the business complexities that your software has been designed to meet. Typically, the business logic layer will fit between your user interface, service, or presentation layer and your data access layer. By separating the business logic from other layers in your applications you are separating your concerns and keeping your code loosely coupled and allowing for different implementations to be used with the business logic layer; for example, changing the UI from a web application to a WPF application.

WPF Win Forms --- Web Forms --- Other Services
-------------------------------------------------------------------
Service Layer
-------------------------------------------------------------------
Business Logic Layer
-------------------------------------------------------------------
Data Access Layer
-------------------------------------------------------------------
Data Sources

Depending on the complexities of the business model that your application has been designed for, the structure of your business logic layer may differ considerably. For instance a complex banking application will have a rich Domain Model that represents the real banking domain with hundreds of small business entities representing loans, customers, and accounts. For a simpler application, such as a blogging engine, you may have a number of fairly simple business objects that map very closely to your underlying Data Model with little or no business logic, simply acting as a method to add and retrieve data. In the next section, you will look at the various patterns at your disposal to structure your business logic layer.

Patterns for Your Business

There are a number of design patterns that you can follow that will help you to organize your business logic. In the below part, you will be introduced to three of the main patterns found in the business logic layer: the Transaction Script, Active Record, and the Domain Model pattern.

Transaction Script

Transaction Script is a very simple business design pattern, which follows a procedural style of development rather than an object - oriented approach. Simply create a single procedure for each of your business transactions with each procedure containing all of the business logic that is required to complete the business transaction from the workflow, business rules, and validation checks to persistence in the database.
One of the strengths of the Transaction Script pattern is that it is very simple to understand and clear to see what is going on without any prior knowledge of the pattern. If a new business case needs to be handled, it is straightforward enough to add a new method to handle it, which will contain all of the related business logic.

The problems with the Transaction Script pattern are revealed when an application grows and the business complexities increase. It is very easy to see many management or application classes with hundreds of fine - grained transaction methods that map directly to a business use cases. Sub methods can be used to avoid repetitive code such as the validation and business rules, but duplication in the workflow cannot be avoided, and the code base can quickly become unwieldy and unmanageable as the application grows.

If you have a simple application with minimal business logic, which doesn’t warrant a fully object - oriented approach, the Transaction Script pattern can be a good fit. However, if your application will grow, you may need to rethink your business logic structure and look to a more scalable pattern like the Active Record pattern.

Active Record Pattern

The Active Record pattern is very popular pattern and is especially effective when your underlying database model matches your business model. Typically, a business object will exist for each table in your database. 
The Active Record pattern is great for very simple applications where there is a one-to-one mapping between the Data Model and the Business Model, such as with a blogging or a forum engine; it ’ s also a good pattern to use if you have an existing database model or tend to build applications with a “ data first ” approach. Because the business objects have a one - to - one mapping to the tables in the database and all have the same CRUD (create, read, update, and delete) methods, it ’ s possible to use code generation tools to auto - generate your business model for you. Good code gen tools will also build in all of the database validation logic to ensure that you are allowing only valid data to be persisted. 

However, the Active Record pattern is no silver bullet. It excels with a good underlying Data Model that maps to the business model, but when there is a mismatch, sometimes called an impedance mismatch, the pattern can struggle to cope. This is the result of complex systems sometimes having a very different conceptual business models than the Data Model. When there is a rich business domain with lots of complex rules, logic, and workflow, this favors going with the Domain Model approach.

Domain Model Pattern

You can think of a Domain Model as a conceptual layer that represents the domain you are working in. Things exist in this model and have relationships to other things. What do I mean by things? Well, for example, if you were building an e - commerce store, the “things” that would live in the model would represent a Basket, Order, and Order Item, and the like. If you were creating a loan application, you would have representations for a Borrower, Loan, Assets, and Debts. It’s these things that have data and, more importantly, behavior. Not only would an order have properties that represent a creation date, status, and order number, but it would also contain the business logic to apply a voucher to, including all of the domain rules that surround it — Is the voucher valid? Can the voucher be used with the products in the basket? Are there any other offers in place that would render the voucher invalid, and so forth. The closer your Domain Model represents the real domain the better, as it will be easier for you to understand and replicate the complex business logic, rules, and validation process. 

The main difference between the Domain Model and the Active Record pattern is that the business entities that live in the Domain Model have no knowledge of how to persist themselves, and there doesn’t necessarily need to be one - to - one mapping between the Data Model and the Business Model.

As mentioned earlier, the Domain Model, unlike the Active Record pattern, has no knowledge of persistence. The term persistence ignorant (PI) has been coined for the plain nature of the POCO(plain old common runtime object) business entities. How then do you persist a business object with the Domain Model? 

Typically, the repository pattern is used. When you are employing the Domain Model pattern, it’s the responsibility of the Repository object, along with a data mapper, to map a business entity and its object graph of associated entities to the Data Model. Be aware that business entities inside the Domain Model are PI.

Trying to solve complex business problems in software is difficult, but when using the Domain Model pattern, you first create an abstract model of the real business model. With this model in place, you can then model complex logic by following the real domain and recreating the workflow and processing in your Domain Model. Another advantage that a Domain Model holds over the Transaction Script and the Active Record patterns is that, because it contains no data access code, it can be easily unit tested without having to mock and stub out dependencies of such a data access layer.

Again, the Domain Model pattern may not always be a great fit for your application needs. One of its great strengths is dealing with complex business logic, but a full - blown Domain Model is architectural overkill when very little business logic is contained within the application. Another disadvantage of the pattern is the steep learning curve needed to become proficient in it compared to the Active Record and Transaction Script options. To use the pattern effectively takes time and experience and, most importantly, a sound knowledge of the business domain you are trying to model.

Which Pattern to Use?

Each pattern has its pros and cons, and there is no one method that will suit all of your development needs. Let’s take a brief look at each pattern and see when it’s most appropriate to use it. 

Transaction Script: If you have a simple application with little or no logic, then Transaction Script is a great choice as a straightforward solution that is easily understood by other developers picking up your code down the line.

Active Record: If your business layer is simply a thin veil over the top of your database, then this is a great pattern to opt for. There are many code generation tools that can automatically create your business objects for you based on your database schema, and it ’ s not too difficult to create your own.

Domain Model: The Domain Model excels when you have an involved, rich complex business domain to model. It’s a pure object - oriented approach that involves creating an abstract model of the real business domain and is very useful when dealing with complex logic and workflow.
The Domain Model is persistence ignorant and relies on mapper classes and the Repository pattern to persist and retrieve business entities.

It now your decision how to implement your application’s Middleware. But keep in mind that a good design will calculate the support time and application extensibility.

Stay tuned for more, and share it with your Development cycle.

Design Patterns Applicability

copyright from: www.dsoftworld.com


Creational Patterns

Abstract factory (Kit)

Use the Abstract Factory pattern when

o A system should be independent of how its products are created, composed, and represented.

o A system should be configured with one of multiple families of products.

o A family of related product objects is designed to be used together, and you need to enforce this constraint.

o You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Builder

Use the Builder pattern when

o The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.

o The construction process must allow different representations for the object that's constructed.

Factory Method (virtual constructor)

Use the Factory Method pattern when

o A class can't anticipate the class of objects it must create.
o A class wants its subclasses to specify the objects it creates.
o Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.


Prototype

Use the Prototype pattern when

o a system should be independent of how its products are created, composed, and represented; 

and

o when the classes to instantiate are specified at run-time, for example, by dynamic loading; 

or

o to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or

o When instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.

Singleton

Use the Singleton pattern when

o There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
o When the sole instance should be extensible by sub classing, and clients should be able to use an extended instance without modifying their code.


Structural Patterns

Adapter (Wrapper)

Use the Adapter pattern when

o You want to use an existing class, and its interface does not match the one you need.

o You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.

o (Object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.


Bridge (Handle/Body)

Use the Bridge pattern when

o You want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.

o Both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.

o Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.

o (C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.

o You have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term "nested generalizations"

o To refer to such class hierarchies.

o You want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client.


Composite

Use the Composite pattern when

o you want to represent part-whole hierarchies of objects.

o you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly.

Decorator (Wrapper)

Use Decorator

o To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.

o For responsibilities that can be withdrawn.

o When extension by subclassing is impractical. Sometimes a large number of independent extensions are

o Possible and would produce an explosion of subclasses to support every combination. Or a class definition

o May be hidden or otherwise unavailable for subclassing.

Façade

Use the Facade pattern when

o You want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they

o Evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more

o Reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A

o Facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients

o Needing more customizability will need to look beyond the facade.

o There are many dependencies between clients and the implementation classes of an abstraction. Introduce a

o facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.

o You want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them Communicate with each other solely through their facades.

FlyWeight

The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true:

o An application uses a large number of objects.

o Storage costs are high because of the sheer quantity of objects.

o Most object state can be made extrinsic.

o Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.

o The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.

Proxy (Surrogate)

Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable:

o A remote proxy provides a local representative for an object in a different address space. Coplien calls this kind of proxy an "Ambassador."

o A virtual proxy creates expensive objects on demand.

o A protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights. For example, KernelProxies in the Choices operating system provide protected access to operating system objects.

o A smart reference is a replacement for a bare pointer that performs additional actions when an object is accessed. Typical uses include counting the number of references to the real object so that it can be freed automatically when there are no more references (also called smart pointers).

o Loading a persistent object into memory when it's first referenced.

o Checking that the real object is locked before it's accessed to ensure that no other object can change it.


Behavioral Patterns

Chain of responsibility

Use Chain of Responsibility when

o More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.

o You want to issue a request to one of several objects without specifying the receiver explicitly the set of objects that can handle a request should be specified dynamically.

Command (Action, Transaction)
Use the Command pattern when

o You want to parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an object-oriented replacement for callbacks.

o Specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address spaceindependent way, then you can transfer a command object for the request to a different process and fulfill the request there.

o Support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.

o Support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes.

o Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.

o Structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.

Interpreter

Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when

o The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases.

o They can interpret expressions without building abstract syntax trees, which can save space and possibly time.

o Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Iterator (Cursor)

Use the Iterator pattern

o To access an aggregate object's contents without exposing its internal representation.

o To support multiple traversals of aggregate objects.

o To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

Mediator

Use the Mediator pattern when

o a set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.

o reusing an object is difficult because it refers to and communicates with many other objects.

o a behavior that's distributed between several classes should be customizable without a lot of subclassing.

Memento (Token)

Use the Memento pattern when

o A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and

o A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.

Observer (Dependents, Publish-Subscribe)

Use the Observer pattern in any of the following situations:

o When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.

o When a change to one object requires changing others, and you don't know how many objects need to be changed.

o When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.

State (Objects for States)

Use the State pattern in either of the following cases:

o An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.

o Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.

Strategy (Policy)

Use the Strategy pattern when

o Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.

o You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms

o An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.

o A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Template Method

The Template Method pattern should be used

o To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.

o When common behavior among subclasses should be factored and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize" as described by Opdyke and Johnson. You first identify the differences in the existing code and then separate the differences into new operations. Finally, you replace the differing code with a template method that calls one of these new operations.

o To control subclasses extensions. You can define a template method that calls "hook" operations at specific points, thereby permitting extensions only at those points

Visitor

Use the Visitor pattern when

o An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.

o Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.

o The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.

reference:
Design Patterns: Elements of Reusable Object-Oriented Software book