# Abstract Factory

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface. An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter and createResume). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter and createResume that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory.
A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes. This allows for new derived types to be introduced with no change to the code that uses the base class.
Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain. Therefore, as in all software designs, the trade-offs must be carefully evaluated.

## Definition

The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes".

## Usage

The factory determines the actual concrete type of object to be created, and it is here that the object is actually created (in C++, for instance, by the new operator). However, the factory only returns an abstract pointer to the created concrete object.
This insulates client code from object creation by having clients ask a factory object to create an object of the desired abstract type and to return an abstract pointer to the object.
As the factory only returns an abstract pointer, the client code (that requested the object from the factory) does not know — and is not burdened by — the actual concrete type of the object that was just created. However, the type of a concrete object (and hence a concrete factory) is known by the abstract factory; for instance, the factory may read it from a configuration file. The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:
* The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.
* Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before — thus insulating the client code from change. This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.

## Structure
### Class diagram

The method createButton on the GuiFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GuiFactory is handling the method call.
Note that, for conciseness, this class diagram only shows the class relations for creating one type of object.

### UML diagram
## Implementations

The output should be either "I'm a WinButton" or "I'm an OSXButton" depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.
This abstract factory creates books.
This abstract factory creates musicians.
Alternative implementation using the classes themselves as factories:
Another example:

# Adapter

The adapter pattern is used when a client class has to call an incompatible provider class. Let's imagine a MailingClient class that needs to call a method on the LegacyEmployee class:
* MailingClient
* +firstName: String +lastName: String
* IEmployee
* +mailEmployee(firstName: String, lastName: String)
* LegacyEmployee
* +mailEmployee(fullName: String)
MailingClient already calls classes that implement the IEmployee interface but the LegacyEmployee doesn't implement it. We could add a new method to LegacyEmployee to implement the IEmployee interface but LegacyEmployee is legacy code and can't be changed. We could modify the MailingClient class to call LegacyEmployee but it needs to change every call. The formatting code would be duplicated everywhere. Moreover, MailingClient won't be able to call other provider class that implement the IEmployee interface any more.
So the solution is to code the formatting code in another independent class, an adapter, also called a wrapper class:
* IEmployee
* +mailEmployee(firstName: String, lastName: String)
* MailingClient
* +firstName: String +lastName: String
* EmployeeAdapter
* +mailEmployee(firstName: String, lastName: String)
* LegacyEmployee
* +mailEmployee(fullName: String)
EmployeeAdapter implements the IEmployee interface. MailingClient calls EmployeeAdapter. EmployeeAdapter formats the data and calls LegacyEmployee. This type of adapter is called an object adapter. The other type of adapter is the class adapter.

## Examples

The WebGL-2D is a JavaScript library that implements the adapter pattern. This library is used for the HTML5 canvas element. The canvas element has two interfaces: 2d and WebGL. The first one is very simple to use and the second is much more complex but optimized and faster. The WebGL-2D 'adapts' the WebGL interface to the 2d interface, so that the client calls the 2d interface only.

## Cost

Think twice before implementing this pattern. This pattern should not be planned at design time. If you plan to use it for a project from scratch, this means that you don't understand this pattern. It should be used only with legacy code. It is the least bad solution.

### Creation

Its implementation is easy but can be expensive. You should not have to refactor the code as the client and the provider should not be able to work together yet.

### Maintenance

This is the worst part. Most of the code has redundancies (but less than without the pattern). The modern interface should always provide as much information as the legacy interface needs to work. If one information is missing on the modern interface, it can call the pattern into question.

### Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

## Advices

* Put the adapter term in the name of the adapter class to indicate the use of the pattern to the other developers.

## Implementation
### Object Adapter

Our company has been created by a merger. One list of employees is available in a database you can access via the CompanyAEmployees class:
One list of employees is available in a LDAP you can access via the CompanyBEmployees class:
To access both to the former employees of the company A and the former employees of the company B, we define an interface that will be used by two adapters, EmployeeBrowser:
We create an adapter for the code of the former company A, CompanyAAdapter:
We create an adapter for the code of the former company B, CompanyBAdapter:

### Class Adapter
# Bridge

Bridge pattern is useful when a code often changes for an implementation as well as for a use of code. In your application, you should have provider classes and client classes:
| Client1 -provider: Provider | Client2 -provider: Provider | ... | ClientN -provider: Provider | ◊— | Provider +doProcess | Provider +doProcess | Provider +doProcess | Provider +doProcess | Provider +doProcess |
| | | | | | Provider1 +doProcess | | Provider2 +doProcess | ... | ProviderN +doProcess |
Each client class can interact with each provider class. However, if the implementation changes, the method signatures of the Provider interface may change and all the client classes have to change. In the same way, if the client classes need a new interface, we need to rewrite all the providers. The solution is to add a bridge, that is to say a class that will be called by the clients, that contains a reference to the providers and forward the client call to the providers.
| Client1 -bridge: Bridge | Client2 -bridge: Bridge | ... | ClientN -bridge: Bridge | ◊— | Bridge -provider: Provider +doProcessForClient | ◊— | Provider +doProcess | Provider +doProcess | Provider +doProcess | Provider +doProcess | Provider +doProcess |
| | | | | | | | Provider1 +doProcess | | Provider2 +doProcess | ... | ProviderN +doProcess |
In the future, the two interfaces (client/bridge and bridge/provider) may change independently and the bridge may trans-code the call order.

## Examples

It's hard to find an example in a library as this pattern is designed for versatile specifications and a library does not change constantly between two versions.

## Cost

The cost of this pattern is the same as the adapter. It can be planned at design time but the best way to decide to add it is the experience feedback. Implement it when you have frequently changed an interface in a short time.

### Creation

Its implementation is easy but can be expensive. It depends on the complexity of the interface. The more methods you have, the more expensive it will be.

### Maintenance

If you always update the client/bridge interface and the bridge/provider interface the same way, it would be more expensive than if you do not implement the design pattern.

### Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

## Advices

* Put the bridge term in the name of the bridge class to indicate the use of the pattern to the other developers.

## Implementation

The following Java (SE 6) program illustrates the bridge pattern.
It will output:
Output:

### C#

The following C# program illustrates the "shape" example given above and will output:

### C# using generics

The following C# program illustrates the "shape" example given above and will output:
The following Python program illustrates the "shape" example given above and will output:
An example in Ruby.
A Scala implementation of the Java drawing example with the same output.
An example in D.
This example in Perl uses the MooseX::Declare module.
The following Delphi program illustrates the "shape" example given above and will output:

# Builder

The builder pattern is useful for avoiding a huge list of constructors for a class. Let's imagine a class that stores the mode of transport (of an employee for instance). Here is the constructor that takes a MetroLine object as a parameter:
* modeOfTransport(MetroLine)
Now we need a constructor for someone who uses the car, the bus or the train:
* new modeOfTransport(MetroLine)
* new modeOfTransport
* new modeOfTransport(BusLine)
* new modeOfTransport(Train)
For some of them, we need to indicate a travel allowance:
* new modeOfTransport(MetroLine)
* new modeOfTransport(MetroLine, Integer)
* new modeOfTransport
* new modeOfTransport(Integer)
* new modeOfTransport(BusLine)
* new modeOfTransport(BusLine, Integer)
* new modeOfTransport(Train)
* new modeOfTransport(Train, Integer)
We have employees who use several modes of transport to go to work. However, we realize that the list of constructors is now becoming a mess. Each new parameter leads to an exponential duplication of constructors. If some parameters have the same type, it becomes very confusing. A solution to this issue would be to first build a fake object and then fill it by calling methods on it:
* new modeOfTransport(MetroLine)
* modeOfTransport.setMetroLine(MetroLine)
* modeOfTransport.setCarTravel
* modeOfTransport.setBusLine(BusLine)
* modeOfTransport.setTrain(Train)
* modeOfTransport.setTravelAllowance(Integer)
The list of methods is no longer exponential but the state of the object may be inconsistent. A better solution would be to set all the parameters to an object of another class, a pre-constructor, and then pass this object to the constructor of ModeOfTransport:
* modeOfTransportPreConstructor.setMetroLine(MetroLine)
* modeOfTransportPreConstructor.setCarTravel
* modeOfTransportPreConstructor.setBusLine(BusLine)
* modeOfTransportPreConstructor.setTrain(Train)
* modeOfTransportPreConstructor.setTravelAllowance(Integer)
* new modeOfTransport(ModeOfTransportPreConstructor)
This solution is even better. We only have a single valid ModeOfTransport object. However, the ModeOfTransport constructor can be called with a half-filled pre-constructor. So the pre-constructor should be a builder and should have a method that returns the ModeOfTransport object. This method will only return an object if the builder has been correctly filled, otherwise it returns null:
* modeOfTransportBuilder.setMetroLine(MetroLine)
* modeOfTransportBuilder.setCarTravel
* modeOfTransportBuilder.setBusLine(BusLine)
* modeOfTransportBuilder.setTrain(Train)
* modeOfTransportBuilder.setTravelAllowance(Integer)
* modeOfTransport := modeOfTransportBuilder.getResult
So the solution is to use a builder class. Let's see the structure of the code in an UML class diagram:
* Builder: Abstract interface for creating objects (product).
* Concrete Builder: Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.
The builder pattern can be used for objects that contain flat data (html code, SQL query, X.509 certificate...), that is to say data that can't be easily edited. This type of data can not be edited step by step and must be edited all at once. The best way to construct such an object is to use a builder class.

## Examples

In Java, the StringBuffer and StringBuilder classes follow the builder design pattern. They are used to build String objects.

## Cost

You can easily decide to use it. At worst, the pattern is useless.

### Creation

Starting from a plain old class with a public constructor, implementing the design pattern is not very expensive. You can create the builder class alongside your code. Then you will have to remove the existing constructor calls to use the builder instead. The refactoring is hardly automatic.

### Maintenance

This design pattern has only small drawbacks. It may lead to small redundancies between the class and the builder structures but the both class have usually different structures. However, it is expensive to convert to an abstract factory.

### Removal

The refactoring is hardly automatic. It should be done manually.

## Advices

* Put the builder term in the name of the builder class to indicate the use of the pattern to the other developers.
* Build your builder class as a fluent interface. It would increase the pattern interest.
* If the target class contains flat data, your builder class can be constructed as a Composite that implements the Interpreter pattern.

## Implementations

Building a car.
It will produce:
Building a pizza.
The Director assembles a bicycle instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client.
Another example:
This C++11 implementation is based on the pre C++98 implementation in the book.
The program output is like:
Another example:
output :

# Chain of responsibility

Various examples of the Chain of responsibility pattern.
Below is an example of this pattern in Java. A logger is created using a chain of loggers, each one configured with different log levels.
The following Java code illustrates the pattern with the example of a logging class. Each logging handler decides if any action is to be taken at this log level and then passes the message on to the next logging handler. Note that this example should not be seen as a recommendation on how to write logging classes.
Also, note that in a 'pure' implementation of the chain of responsibility pattern, a logger would not pass responsibility further down the chain after handling a message. In this example, a message will be passed down the chain whether it is handled or not.
The output is:
Below is another example of this pattern in Java. In this example we have different roles, each having a fix purchase power limit and a successor. Every time a user in a role receives a purchase request, when it's over his limit, he just passes that request to his successor.
The PurchasePower abstract class with the abstract method processRequest.
Four implementations of the abstract class above: Manager, Director, Vice President, President
The PurchaseRequest class with its Getter methods which keeps the request data in this example.
And here a usage example, the successors are set like this: Manager -> Director -> Vice President -> President
Another example:
Output
Java example about purchase power of various roles, using perl 5.10 and Moose.
Perl example using perl 5.10 and Moose.
This C# examples uses the logger application to select different sources based on the log level;
Another example:

# Command

The command pattern is an object behavioural pattern that decouples sender and receiver. It can also be thought as an object-oriented equivalent of a call back method. Call back: It is a function that is registered to be called at a later point of time based on user actions.

## Scope

Object

## Purpose

Behavioral

## Intent

Encapsulate the request for a service as an object.

## Applicability

* to parameterize objects with an action to perform
* to specify, queue, and execute requests at different times
* for a history of requests
* for multilevel undo/redo

## Consequences

* + abstracts executor of a service
* + supports arbitrary-level undo-redo
* + composition yields macro-commands
* - might result in lots of trivial command subclasses

## Examples

The best example for this pattern is the graphical user interface. On most multidata interfaces, you have both a "New" menu and a "New" button with an icon like in Libre Office Writer. Both controls are connected to a command object, so the action is performed by the same code.

## Cost

This pattern is dealing with the whole architecture of a program. It may have a substantial impact on the project.

### Creation

If the code already exists, this pattern is very expensive.

### Maintenance

This pattern is very expensive to maintain.

### Removal

This pattern is very expensive to remove, too.

## Advises

* Use the Command term to indicate the use of the pattern to the other developers.

## Implementations

Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off. A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light — the Switch in the following example turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.

## Operations

The implementations to do are:
* copying a command before putting it on a history list
* handling hysteresis
* supporting transactions
In the above example, it can be noted that the command pattern decouples the object that invokes the operation from the ones having the knowledge to perform it.

### Command in Java

Menus and buttons provide a classic example of the need for the command pattern. When you add a menu to an application, you have to configure the menu with words that describe actions that the user can choose, such as Save and Open. Similarly for a button. You also have to configure the menu or button so that it can take action, calling a method in response to a user's click. However, JMenuItem or JButton class has no way of knowing what action to perform when an item or button is selected. In the following example we use the same Action for both a menu item and a button saving us from having to write the same code twice.
Java Swing applications commonly apply the Mediator pattern, registering a single object to receive all GUI events. This object mediates the interaction of the components and translates user input into commands for business domain objects.

### Undo in Java

Swing provides for Undo/Redo functionality.
Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off.
A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light. The Switch in the following C# implementation turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.
The following code is another implementation of command pattern in C#.
The following code is an implementation of command pattern in Python.
The following code is an implementation of command pattern in Javascript.
The following code is an implementation of command pattern in PHP.

# Composite

The composite design pattern reduces the cost of an implementation that handles data represented as a tree. When an application does a process on a tree, usually the process has to handle the iteration on the components, the move on the tree and has to process the nodes and the leafs separately. All of this creates a big amount of code. Suppose that you have to handle a file system repository. Each folders can contain files or folders. To handle this, you have an array of items that can be file or folder. The files have a name and the folders are arrays. Now you have to implement a file search operation on the whole folder tree. The pseudo-code should look like this:
In the previous code, each iteration of the same while loop is a process of one node or leaf. At the end of the process, the code move to the position of the next node or leaf to process. There are three branches in the loop. The first branch is true when we have processed all the children of the node and it moves to the parent, the second goes into a child node and the last process a leaf (i.e. a file). The memory of the location should be stored to go back in the tree. The problem in this implementation is that it is hardly readable and the process of the folders and the files is completely separate. This code is heavy to maintain and you have to think to the whole tree each moment. The folders and the files should be called the same way so they should be objects that implements the same interface.

## Component

* is the abstraction for all components, including composite ones.
* declares the interface for objects in the composition.
* (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.

## Leaf

* represents leaf objects in the composition.
* implements all Component methods.

## Composite

* represents a composite Component (component having children).
* implements methods to manipulate children.
* implements all Component methods, generally by delegating them to its children.
So now the implementation is rather like this:
As you can see, a component can be an individual object and also can be a collection of objects. A Composite pattern can represent both the conditions. In this pattern, one can develop tree structures for representing part-whole hierarchies.

## Examples

The best example of use of this pattern is the Graphical User Interface. The widgets of the interface are organized in a tree and the operations (resizing, repainting...) on all the widgets are processed using the composite design pattern.

## Cost

This pattern is one of the least expensive patterns. You can implement it each time you have to handle a tree of data without worrying. There is no bad usage of this pattern. The cost of the pattern is only to handle the children of a composite but this cost would be required and more expensive without the design pattern.

### Creation

You have to create an almost empty interface and implement the management of the composite children. This cost is very low.

### Maintenance

You can't get caught in the system. The only relatively expensive situation occurs when you have to often change the operations applied to the whole data tree.

### Removal

You should remove the pattern when you remove the data tree. So you just remove all in once. This cost is very low.

## Advices

* Put the composite and component terms in the name of the classes to indicate the use of the pattern to the other developers.

## Implementations

Various examples of the composite pattern.
The following example, written in Common Lisp, and translated directly from the Java example below it, implements a method named print-graphic, which can be used on either an ellipse, or a list whose elements are either lists or ellipses.
The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In Backus-Naur form,
It could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).
The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In algebraic form,
It could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).

# Decorator

The decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”.

## Cost

This pattern can be very expensive. You should only use it when it is really necessary. You should have lots of different behaviors and responsibilities for the same class.

### Creation

This pattern is expensive to create.

### Maintenance

This pattern can be expensive to maintain. If the representation of a class often changes, you will have lots of refactoring.

### Removal

This pattern is hard to remove too.

## Advises

* Put the decorator term in the name of the decorator classes to indicate the use of the pattern to the other developers.

## Implementations

This example illustrates a simple extension method for a bool type.

## Coffee making scenario

The output of this program is given below:
Whip Milk Coffee Cost: 2.2
The output of this program is given below:
Cost: 1.0; Ingredients: Coffee Cost: 1.5; Ingredients: Coffee, Milk Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles

## First Example (window/scrolling scenario)

The following Java example illustrates the use of decorators using the window/scrolling scenario.
The following classes contain the decorators for all Window classes, including the decorator classes themselves.
Here's a test program that creates a Window instance which is fully decorated (i.e., with vertical and horizontal scrollbars), and prints its description:
The output of this program is "simple window, including vertical scrollbars, including horizontal scrollbars". Notice how the getDescription method of the two decorators first retrieve the decorated Window's description and decorates it with a suffix.

## Second Example (coffee making scenario)

The next Java example illustrates the use of decorators using coffee making scenario. In this example, the scenario only includes cost and ingredients.
The following classes contain the decorators for all Coffee classes, including the decorator classes themselves..
Here's a test program that creates a Coffee instance which is fully decorated (i.e., with milk, whip, sprinkles), and calculate cost of coffee and prints its ingredients:
The output of this program is given below:
Cost: 1.0 Ingredient: Coffee Cost: 1.5 Ingredient: Coffee, Milk Cost: 1.7 Ingredient: Coffee, Milk, Sprinkles Cost: 2.4 Ingredient: Coffee, Milk, Sprinkles, Whip

## Coffee example
### Dynamic languages

The decorator pattern can also be implemented in dynamic languages either with interfaces or with traditional OOP inheritance.

## External links

* Java Design Patterns tutorial
* History of Design Patterns

# Facade

A Facade pattern hides the complexities of the system and provides an interface to the client from where the client can access the system. Dividing a system into subsystems helps reduce complexity. We need to minimize the communication and dependencies between subsystems. For this, we introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.

## Examples

The SCP command is a shortcut for SSH commands. A remote file copy could be done writing several commands with an SSH connection but it can be done in one command with SCP. So the SCP command is a facade for the SSH commands. Although it may not be coded in the object programming paradigm, it is a good illustration of the design pattern.

## Cost

This pattern is very easy and has not additional cost.

### Creation

This pattern is very easy to create.

### Maintenance

This pattern is very easy to maintain.

### Removal

This pattern is very easy to remove too.

## Advises

* Do not use this pattern to mask only three or four method calls.

## Implementations

This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

# Factory method

The factory pattern is a design pattern used to promote encapsulation of data representation.

## Problem

    We want to decide at run time what object is to be created based on some configuration or application parameter. When we write the code we do not know what class should be instantiated.

## Solution

    Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Its primary purpose is to provide a way for users to retrieve an instance with a known compile-time type, but whose runtime type may actually be different. In other words, a factory method that is supposed to return an instance of the class Foo may return an instance of the class Foo, or it may return an instance of the class Bar, so long as Bar inherits from Foo. The reason for this is that it strengthens the boundary between implementor and client, hiding the true representation of the data (see Abstraction Barrier) from the user, thereby allowing the implementor to change this representation at anytime without affecting the client, as long as the client facing interface doesn't change.

## Basic Implementation of the Factory Pattern

The general template for implementing the factory pattern is to provide a primary user facing class with static methods which the user can use to get instances with that type. Constructors are then made private/protected from the user, forcing them to use the static factory methods to get objects. The following Java code shows a very simple implementation of the factory pattern for type Foo.
With this code, it would be impossible for a client of the code to use the new operator to get an instance of the class, as is traditionally done:
because the constructor is marked private. Instead, the client would have to use the factory method:
It should be noted that even within a programming language community, there is no general consensus as to the naming convention of a factory method. Some suggest naming the method with the name of the class, similar to a normal constructor, but starting with a lowercase. Others say that this is confusing, and suggest using an accessor type syntax, like the getInstance style used above, though others complain that this may incorrectly imply a singleton implementation. Likewise, some offer newInstance, but this is criticized as being misleading in certain situations where a strictly new instance may not actually be returned (once again, refer to the singleton pattern). As such, we will not attempt to follow any particularly rigid standard here, we will simply try to use a name that makes the most sense for our current purposes.

## Factory Pattern Implementation of the Alphabet

That's great, you know how to implement a real simple factory pattern, but what good did it do you? Users are asking for something that fits into type Foo, and they're getting an instance of the class Foo, how is that different from just calling the constructor? Well it's not, except that you're putting another function call on the stack (which is a bad thing). But that's only for the above case. We'll now discuss a more useful use of the factory pattern. Consider a simple type called Letter, representing a letter in the alphabet, which has the following client facing interface (i.e., public instance methods):
We could implement this easily enough without using the factory method, which might start out something like this:
Fairly simple, but notice we haven't implemented the last two methods yet. We can still do it pretty easily. The first might look like this:
Now that's not too bad, but we still need to do isConsonant. Fortunately, we at least know in this case that if it's a vowel, it's not a consonant, and vice versa, so our last method could simply be:
So what's the problem here? Basically, every time you call either of these methods, your program has to do all that checking. Granted, this isn't a real heavy burden for the Java Runtime Environment, but you can imagine a much more complex, much more time consuming operation. Wouldn't it be great if we could avoid doing this every time we call the method? Let's say, for instance, we could do it once when we create the object, and then not have to do it again. Well sure, we can do that. Here's an implementation that'll do that for us, and we still don't have to use the factory method:
Notice how we moved the lengthy operation into the constructor, and stored the result. OK, so now we're all fine and dandy, no? Sure, but let's say you came up with a new idea, a different implementation: you want to split this type into two classes, one class to handle the vowels, and one to handle the consonants. Great, they can both be subclasses of the Letter class, and the user will never know the difference, right? Wrong. How is the client supposed to get at these new classes? They've got code that works perfectly well for them by calling new Letter('a') and new Letter('Z'). Now you're going to make them go through all their code and change these to new Vowel('a') and new Consonant('Z')? They probably won't be too happy with that. If only you could get new instances of both classes from one method! Well you can, just use a static method in the Letter class, it'll do the same one-time checking as the constructor did, and will return an appropriate instance of the right class. And what do you know, it's a factory method! But that still doesn't do your client much good, they still need to go through and change all the new Letters into Letter.getLetter. Well, sad to say, it's too late to help them at all, unless you just give up your new implementation. But that illustrates the reason for using the factory method right off the bat. One of the key components of good object oriented programming is that you never know exactly where your code will go in the future. By making good use of the abstraction barrier and using encapsulation-friendly programming patterns, such as the factory pattern, you can better prepare yourself—and your client—for future changes to the specific implementation. In particular, it allows you to use a "big hammer" kind of approach to get something done in a perhaps-less-than-ideal but rapid manner in order to meet deadlines or move ahead with testing,. You can then go back later and refine the implementation—the data representation and algorithms—to be faster, smaller, or what-have-you, and as long as you maintained the abstraction barrier between implementor and client and properly encapsulated your implementation, then you can change it without requiring the client to change any of their code. Well now that I'm sure you're a raving advocate for the factory method, let's take a look at how we would implement it for our Letter type:
Several things to note here.
* First, you'll notice the top level class Letter is abstract. This is fine because you'll notice that it doesn't actually do anything except define the interface and provide a top level container for the two other classes. However, it's also important (not just OK) to make this abstract because we don't want people trying to instantiate the Letter class directly. Of course we could solve this problem by making a private constructor, but making the class abstract instead is cleaner, and makes it more obvious that the Letter class is not meant to be instantiated. It also, as mentioned, allows us to define the user facing interface that the work horse classes need to implement.
* The two nested classes we created are called local classes, which is basically the same as an inner class except that local classes are static, and inner classes are not. They have to be static so that our static factory method can create them. If they were non static (i.e., dynamic) then they could only be accessed through an instance of the Letter class, which we can never have because Letter is abstract. Also note that (in Java, anyway) the fields for inner and local classes typically use the "i" (for inner) prefix, as opposed to the "f" (for field) prefix used by top level classes. This is simply a naming convention used by many Java programmers and doesn't actually effect the program.
* The two nested classes that implement the Letter data type do not actually have to be local/inner. They could just have easily been top level classes that extend the abstract Letter class. However, this is contrary to the point of the factory pattern, which is encapsulation. Top level classes can't be private in Java, because that doesn't make any sense (what are they private to?) and the whole point is that no client has to (or should, really) know how the type is implemented. Making these classes top level allows clients to potentially stumble across them, and worse yet, instantiate them, by-passing the factory pattern all together.
* Lastly, this is not very good code. There's a lot of ways we can make it better to really illustrate the power of the factory pattern. I'll discuss these refactorings briefly, and then show another, more polished, version of the above code which includes a lot of them.

### Refactoring the Factory Pattern

Notice that both of the local classes do the same thing in a few places. This is redundant code which is not only more work to write, but it's also highly discouraged in object oriented programming (partially because it takes more work to write, but mostly because it's harder to maintain and prone to errors, e.g., you find a bug in the code and change it in one spot, but forget to in another.) Below is a list of redundancies in the above code:
* The field iTheLetter
* The method getLetter
* The constructor of each inner class does the same thing.
In addition, as we discovered above, the isVowel and isConsonant just happen to always return the opposite of each other for a given instance. However, since this is something of a peculiarity for this particular example, we won't worry about it. The lesson you would learn from us doing that will already be covered in the refactoring of the getLetter method. OK, so we have redundant code in two classes. If you're familiar with abstracting processes, then this is probably a familiar scenario to you. Often, having redundant code in two different classes makes them prime candidates for abstraction, meaning that a new abstract class is created to implement the redundant code, and the two classes simply extend this new abstract class instead of implementing the redundant code. Well what do you know? We already have an abstract super class that our redundant classes have in common. All we have to do is make the super class implement the redundant code, and the other classes will automatically inherit this implementation, as long as we don't override it. So that works fine for the getLetter method, we can move both the method and the iTheLetter field up to the abstract parent class. But what about the constructors? Well our constructor takes an argument, so we won't automatically inherit it, that's just the way java works. But we can use the super keyword to automatically delegate to the super classes constructor. In other words, we'll implement the constructor in the super class, since that's where the field is anyway, and the other two classes will delegate to this method in their own constructors. For our example, this doesn't save much work, we're replacing a one line assignment with a one line call to super, but in theory, there could be hundred of lines of code in the constructors, and moving it up could be a great help. At this point, you might be a little worried about putting a constructor in the Letter class. Didn't I already say not to do that? I thought we didn't want people trying to instantiate Letter directly? Don't worry, the class is still abstract. Even if there's a concrete constructor, Java won't let you instantiate an abstract class, because it's abstract, it could have method that are accessible but undefined, and it wouldn't know what to do if such a method was invoked. So putting the constructor in is fine. After making the above refactorings, our code now looks like this:
Note that we made our abstracted field protected. This isn't strictly necessary in this case, we could have left it private, because the subclasses don't actually need to access it at all. In general, I prefer to make things protected instead of private, since, as I mentioned, you can never really be sure where a project will go in the future, and you may not want to restrict future implementors (including yourself) unnecessarily. However, many people prefer to default to private and only use protected when they know it's necessary. A major reason for this is the rather peculiar and somewhat unexpected meaning of protected in Java, which allows not only subclasses, but anything in the same package to access it. This is a bit of a digression, but I think it's a fairly important debate that a good Java programmer should be aware of.

## The Factory Pattern and Parametric Polymorphism

The version of the Java Virtual Machine 5.0 has introduced something called Parametric Polymorphism, which goes by many other names in other languages, including "generic typing" in C++. In order to really understand the rest of this section, you should read that section first. But basically, this means that you can introduce additional parameters into a class—parameters which are set at instantiation—that define the types of certain elements in the class, for instance fields or method return values. This is a very powerful tool which allows programmers to avoid a lot of those nasty instanceofs and narrowing castes. However, the implementation of this device in the JVM does not promote the use of the Factory pattern, and in the two do not play well together. This is because Java does not allow methods to be parameterized the way types are, so you cannot dynamically parameterize an instance through a method, only through use of the new operator. As an example, imagine a type Foo which is parameterized with a single type which we'll call T. In java we would write this class like this:
Now we can have instances of Foo parameterized by all sorts of types, for instance:
But let's say we want to use the factory pattern for Foo. How do we do that? You could create a different factory method for each type you want to parameterize over, for instance:
But what about something like the ArrayList class (in the java.util package)? In the java standard libraries released with 5.0, ArrayList is parameterized to define the type of the object stored in it. We certainly don't want to restrict what kinds of types it can be parameterized with by having to write a factory method for each type. This is often the case with parameterized types: you don't know what types users will want to parameterize with, and you don't want to restrict them, so the factory pattern won't work for that. You are allowed to instantiate a parameterized type in a generic form, meaning you don't specify the parameter at all, you just instantiate it the way you would have before 5.0. But that forces you to give up the parameterization. This is how you do it with generics:

## Examples

In Java, a class that implements java.sql.Connection is a factory of statements. By calling the createStatement method, you create a statement for which you only know the interface. The factory chooses the right instance class for you.

## Cost

This pattern is not so expensive when it is implemented at the right time. It can be more expensive if you have to refactor an existing code.

### Creation

Its implementation is easy and there is no additional cost (it is not more expensive than an implementation without this pattern).

### Maintenance

There is no additional cost nor additional constraint.

### Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

## Good practices

* Name the factory class with the instanciated class in prefix and the factory term in suffix, to indicate the use of the pattern to the other developers.
* Avoid to persist the factory result (in database) into the factory class, to respect the SOLID principles and allow the creation of ephemeral objects, for example into the automatic tests.

## Implementation

This C++11 implementation is based on the pre C++98 implementation in the book.
The program output is like:
In Common Lisp, factory methods are not really needed, because classes and class names are first class values.

## Example with pizza

Output:

## Another example with image
### Abstract creator

    Interface to create the Product.

### Concrete creator

    a class to create specific Product.

### Factory class

    a class to return a specific concrete creator at runtime to create the product.
This example in JavaScript uses Firebug console to output information.
Output
Usage example:
Factories are not really needed for this example in Perl, and this may be written more concisely:
Output
As in Perl, Common Lisp and other dynamic languages, factories of the above sort aren't really necessary, since classes are first-class objects and can be passed around directly, leading to this more natural version:
Note in the above that the classes themselves are simply used as values, which pizza_class iterates over. The class gets created simply by treating it as a function. In this case, if pizza_class holds a class, then pizza_class creates a new object of that class. Another way of writing the final clause, which sticks more closely to the original example and uses strings instead of class objects, is as follows:
In this case, the correct class name is constructed as a string by adding 'Pizza', and eval is called to turn it into a class object.

# Flyweight

It is a mechanism by which you can avoid creating a large number of object instances to represent the entire system. To decide if some part of a program is a candidate for using Flyweights, consider whether it is possible to remove some data from the class and make it extrinsic.

## Examples

A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally. Another example is string interning.
In video games, it is usual that you have to display the same sprite (i.e. an image of an item of the game) several times. It would highly use the CPU and the memory if each sprite was a different object. So the sprite is created once and then is rendered at different locations in the screen. This problem can be solved using the flyweight pattern. The object that renders the sprite is a flyweight.

## Cost

There are several implementations for this pattern. So it's up to you to find a cheap implementation. Only implement this pattern if you have or will have CPU or memory issues.

### Creation

This pattern is quite easy to create.

### Maintenance

This pattern is quite easy to maintain.

### Removal

This pattern is quite easy to remove too.

## Advises

* Use pre-existing tools from the language like the sets in Java.

## Implementations

The following programs illustrate the document example given above: the flyweights are called FontData in the Java example. The examples illustrate the flyweight pattern used to reduce memory by loading only the data necessary to perform some immediate task from a large Font object into a much smaller FontData (flyweight) object.

# Interpreter

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

## Examples

The following Reverse Polish notation example illustrates the interpreter pattern. The grammar:
expression ::= plus | minus | variable | number plus ::= expression expression '+' minus ::= expression expression '-' variable ::= 'a' | 'b' | 'c' | ... | 'z' digit ::= '0' | '1' | ... '9' number ::= digit | digit number
defines a language which contains reverse Polish expressions like:
a b + a b c + - a b + c a - -
Following the interpreter pattern there is a class for each grammar rule.

## Cost

This pattern is not expensive. It dramatically reduces the business code so there is only few code to handle.

### Creation

If the code already exists, this pattern is a little expensive.

### Maintenance

This pattern is very easy to maintain. There is no additional cost due to the pattern.

### Removal

This pattern is easy to remove with refactoring operations from your IDE.

## Advises

* Use the Interpreter term to indicate the use of the pattern to the other developers.

## Implementations

The following Backus–Naur form example illustrates the interpreter pattern. The grammar
defines a language that contains Reverse Polish Notation expressions like:
This structural code demonstrates the Interpreter patterns, which using a defined grammar, provides the interpreter that processes parsed statements.
Another example:
While the interpreter pattern does not address parsing, a parser is provided for completeness.
Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.
Another example:
While the interpreter pattern does not address parsing a parser is provided for completeness.
Finally evaluating the expression "w x z - +" with w = 5, x = 10, and z = 42.
As JavaScript is dynamically typed, we do not implement an interface.
Example 1:
Example 2: Based on the example above with another realization of the client.
Example 3: In a file we have the classes and the interface, defining the logic of the program (and applying the Interpreter pattern). Now the expr.php file:
And the evaluate.php:
And you can run on a terminal by typing php5 -f evaluator.php (or putting it on a web application).

# Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

## Examples

In Java, the interface java.util.Iterator<E> is an implementation of the iterator pattern. That way, all the objects that implement the java.lang.Iterable<T> interface don't need a handy implementation of this pattern.

## Cost

This pattern has a cost. Only implement this pattern for an important amount of code. IDE refactoring can't help you much.

### Creation

This pattern has a cost to create.

### Maintenance

This pattern is easy to maintain.

### Removal

This pattern has a cost to remove too.

## Advises

* Put the iterator term in the name of the iterator class to indicate the use of the pattern to the other developers.

## Implementations

Java has the Iterator interface.
A simple example showing how to return integers between [start, end] using an Iterator
As of Java 5, objects implementing the Template:Javadoc:SE interface, which returns an Iterator from its only method, can be traversed using Java's foreach loop syntax. The Template:Javadoc:SE interface from the Java collections framework extends Iterable.
Here is another example in Java:
Two different usage examples:
JavaScript, as part of ECMAScript 6, supports the iterator pattern with any object that provides a next method, which returns an object with two specific properties: done and value. Here's an example that shows a reverse array iterator:
Most of the time, though, it is desirable to provide Iterator semantics on objects so that they can be iterated automatically via for...of loops. Some of JavaScript's built-in types such as Array, Map, or Set already define their own iteration behavior. The same effect can be achieved by defining an object's meta @@iterator method, also referred to by Symbol.iterator. This creates an Iterable object.
Here's an example of a range function that generates a list of values starting from start to end, exclusive, using a regular for loop to generate the numbers:
The iteration mechanism of built-in types, like strings, can also be manipulated:
.NET Framework has special interfaces that support a simple iteration: System.Collections.IEnumerator over a non-generic collection and System.Collections.Generic.IEnumerator<T> over a generic collection.
C# statement foreach is designed to easily iterate through the collection that implements System.Collections.IEnumerator and/or System.Collections.Generic.IEnumerator<T> interface. Since C# v2, foreach is also able to iterate through types that implement System.Collections.Generic.IEnumerable<T> and System.Collections.Generic.IEnumerator<T>
Example of using foreach statement:
Here is another example in C#:
PHP supports the iterator pattern via the Iterator interface, as part of the standard distribution. Objects that implement the interface can be iterated over with the foreach language construct.
Example of patterns using PHP:

#### Output

Another example: As a default behavior in PHP 5, using an object in a foreach structure will traverse all public values. Multiple Iterator classes are available with PHP to allow you to iterate through common lists, such as directories, XML structures and recursive arrays. It's possible to define your own Iterator classes by implementing the Iterator interface, which will override the default behavior. The Iterator interface definition:
These methods are all being used in a complete foreach( $object as $key=>$value ) sequence. The methods are executed in the following order:
According to Zend, the current method is called before and after the valid method.
In Perl, objects providing an iterator interface either overload the <> (iterator operator), or provide a hash or tied hash interface that can be iterated over with each. Both <> and each return undef when iteration is complete. Overloaded <> operator:
Iterating over a hash (or tied hash):
Python prescribes a syntax for iterators as part of the language itself, so that language keywords such as for work with what Python calls iterables. An iterable has an __iter__ method that returns an iterator object. The "iterator protocol" requires next return the next element or raise a StopIteration exception upon reaching the end of the sequence. Iterators also provide an __iter__ method returning themselves so that they can also be iterated over; e.g., using a for loop. Generators are available since 2.2.
In Python 3, next was renamed __next__.
In Python, iterators are objects that adhere to the iterator protocol. You can get an iterator from any sequence (i.e. collection: lists, tuples, dictionaries, sets, etc.) with the iter method. Another way to get an iterator is to create a generator, which is a kind of iterator. To get the next element from an iterator, you use the next method (Python 2) / next function (Python 3). When there are no more elements, it raises the StopIteration exception. To implement your own iterator, you just need an object that implements the next method (Python 2) / __next__ method (Python 3). Here are two use cases:
Raku provides APIs for iterators, as part of the language itself, for objects that can be iterated with for and related iteration constructs, like assignment to a Positional variable. An iterable must at least implement an iterator method that returns an iterator object. The "iterator protocol" requires the pull-one method to return the next element if possible, or return the sentinel value IterationEnd if no more values could be produced. The iteration APIs is provided by composing the Iterable role, Iterator, or both, and implementing the required methods.
To check if a type object or an object instance is iterable, the does method can be used:
The does method returns True if and only if the invocant conforms to the argument type.
Here's an example of a range subroutine that mimics Python's range function:
MATLAB supports both external and internal implicit iteration using either "native" arrays or cell arrays. In the case of external iteration where the onus is on the user to advance the traversal and request next elements, one can define a set of elements within an array storage structure and traverse the elements using the for-loop construct. For example,
traverses an array of integers using the for keyword. In the case of internal iteration where the user can supply an operation to the iterator to perform over every element of a collection, many built-in operators and MATLAB functions are overloaded to execute over every element of an array and return a corresponding output array implicitly. Furthermore, the arrayfun and cellfun functions can be leveraged for performing custom or user defined operations over "native" arrays and cell arrays respectively. For example,
defines a primary function simpleFun which implicitly applies custom subfunction myCustomFun to each element of an array using built-in function arrayfun.
Alternatively, it may be desirable to abstract the mechanisms of the array storage container from the user by defining a custom object-oriented MATLAB implementation of the Iterator Pattern. Such an implementation supporting external iteration is demonstrated in MATLAB Central File Exchange item Design Pattern: Iterator (Behavioural). This is written in the new class-definition syntax introduced with MATLAB software version 7.6 (R2008a)
and features a one-dimensional cell array realisation of the List Abstract Data Type (ADT) as the mechanism for storing a heterogeneous (in data type) set of elements. It provides the functionality for explicit forward List traversal with the hasNext, next and reset methods for use in a while-loop.

## References

* ↑ "Iterators and generators". Retrieved 18 March 2016.
* ↑ "C# foreach statement".
* ↑ "PHP: Iterator". Retrieved 23 June 2013.
* ↑ File handle objects implement this to provide line by line reading of their contents
* ↑ In Perl 5.12, arrays and tied arrays can be iterated over like hashes, with each
* ↑ "Python v2.7.1 documentation: The Python Standard Library: 5. Built-in Types". Retrieved 2 May 2011.
* ↑ "Raku documentation: role Iterable". Retrieved 9 December 2020.
* ↑ "Raku documentation: role Iterator". Retrieved 9 December 2020.
* ↑ "New Class-Definition Syntax Introduced with MATLAB Software Version 7.6". The MathWorks, Inc. March 2009. Retrieved September 22, 2009.

# Mediator

This pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. This pattern helps to model a class whose object at run-time is responsible for controlling and coordinating the interactions of a group of other objects.

## Participants

Mediator — defines the interface for communication between Colleague objects. ConcreteMediator — implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication. ConcreteColleague — communicates with other Colleagues through its Mediator.

## Cost

This pattern is not expensive because there is not much constraint on it.

### Creation

This pattern is easy to create.

### Maintenance

This pattern is easy to maintain.

### Removal

Each object can easily be transformed to another structure using refactoring.

## Advises

* Put the mediator term in the name of the iterator class to indicate the use of the pattern to the other developers.

## Implementations
# Memento

Briefly, the Originator (the object to be saved) creates a snap-shot of itself as a Memento object, and passes that reference to the Caretaker object. The Caretaker object keeps the Memento until such a time as the Originator may want to revert to a previous state as recorded in the Memento object.
The following Java program illustrates the "undo" usage of the Memento Pattern.
The output is:

## C# Example
## Another way to implement memento in C#

Output:

# Model–view–controller

The model-view-controller (MVC) pattern is an architectural pattern used primarily in creating Graphic User Interfaces (GUIs). The major premise of the pattern is based on modularity and it is to separate three different aspects of the GUI: the data (model), the visual representation of the data (view), and the interface between the view and the model (controller). The primary idea behind keeping these three components separate is so that each one is as independent of the others as possible, and changes made to one will not affect changes made to the others. In this way, for instance, the GUI can be updated with a new look or visual style without having to change the data model or the controller.
Newcomers will probably see this MVC pattern as wasteful, mainly because you are working with many extra objects at runtime, when it seems like one giant object will do. But the secret to the MVC pattern is not writing the code, but in maintaining it, and allowing people to modify the code without changing much else. Different developers have different strengths and weaknesses, so team building around MVC is easier. Imagine a View Team that is responsible for great views, a Model Team that knows a lot about data, and a Controller Team that sees the big picture of application flow, handing requests, working with the model, and selecting the most appropriate next view for that client.
One of the great advantages of the Model-View-Controller Pattern is the ability to reuse the application's logic (which is implemented in the model) when implementing a different view. A good example is found in web development, where a common task is to implement an external API inside of an existing piece of software. If the MVC pattern has cleanly been followed, this only requires modification to the controller, which can have the ability to render different types of views dependent on the content type requested by the user agent.

## Model

Generally, the model is constructed first. The model has two jobs: it must both store a state and manage subscribers. The state does not need to be anything special; you simply need to define how you're going to store data, with setters and getters. However, anything which can change (any property) must have a list of listeners which it contacts whenever the value changes. The property listeners allow us to have multiple views on the same data, which are all live-updated when the state changes. The code for this can usually be defined in a superclass and inherited, so that you just write it in one place and then it applies consistently to every property. Nested states (for example, dynamically configured properties) may require some extra thinking about how you want to report the changes.
People sometimes use the word 'model' to refer to the 'data model' -- the architecture of the data structures in the application. A good MVC framework takes care of the model superclass and subscriptions for you, so that you can simply define your own data structure in that framework's model-language, and then immediately build the other components. In this end-user sense, defining the data model is equivalent to defining a model. However, if you are designing a framework, it is not MVC if it lacks property listeners.

## View

Once you write a data model, the next easiest thing to write is usually a view. The view is the part of the application which subscribes to a model. Usually it presents it to a user alongside a user interface, or GUI. The GUI contains other components too, which are usually part of the controller and can be handled later.
You can also have view-controller components which have nothing to do with user interfaces. You can imagine, for example, an MVC circuit-board application where a model simply manages numbers (voltages and currents) throughout the circuit. A resistor, for example, then has a "view" of the voltages at each end, tightly coupled to a "controller" which updates the current going through that resistor. All of the components talking to each other through the model would then eventually perform the circuit's actions in real-time.
When you're writing a view, there are two things to think about: "what do I do when the state changes?" and "how do I display this to the user?" Your MVC framework usually provides editors for various properties in the model, like date selectors, text fields, sliding bars, and combo boxes. More complex properties often require more complex views and editors, like tree views. Your MVC framework will probably have already figured out how to connect these components to the model, and might even auto-generate appropriate components based on the type of a given property in the model.

## Controller

The rest of the GUI -- the parts which do not update when the model changes -- are the responsibility of the controller. This includes navigating around the view, as well as what you do when someone tries to edit the data in the view. Strictly speaking, a view cannot be edited and is 'read-only' -- when you try to modify a field in the view, the controller needs to pick up the editing event, process it, and send it to the model; the model will then update the view if/when the value actually changes.
Different frameworks handle controllers in different ways. Some frameworks allow callback functions to be associated with editors, which get called when the value is changed. Other frameworks allow you to add listeners directly to the component, which can be notified when the value in the editor changes, when it is clicked on, or when it loses focus, etc. In many frameworks, the controller appears as a collection of methods and listeners built into both the data model and the view. For example, if you have a "password" property in the model which needs to be salted and hashed before being stored, this logic might appear in a setPassword function living in the data model. Similarly, when a framework generates a view, the widgets for the view are often not read-only but rather read-write, with listeners. The actual controllers provided by the MVC framework then "plug into" each of these interfaces, and pass data between them.

### Validation

When possible, it is usually best to allow the model to do all the necessary validation of values, so that any changes to the allowed values, or changes simply to the validation process, only need to be made in one place. However, in some languages under certain circumstances, this may not be possible. For instance, if a numeric property is being edited with a text field, then the value of the property passed to the controller by the view will be text, not a number. In this case, the model could be made to have an additional method that takes text as the input value for this property, but more likely, the controller will do the initial parsing of the text to get the numeric value, and then pass it on to the model to do further validation (for instance, bounds checking). When either the controller or the model determines that a passed in value is invalid, the controller will need to tell the view that the value is invalid. In some cases, the view may then issue an error dialog or other notification, or it may simply revert the value in its editor to the older valid value.
In Java, we can implement a fat client GUI. In this case, we can use:
* JavaBeans to implement the model and,
* SWT or Java Swings to implement the view and the controller.
However, in Java EE, we can also implement a web application. In this case, we can use:
* EJB entity to implement the model,
* JSP to implement the view and,
* EJB session to implement the controller.

# Observer
## Scope

Object

## Purpose

Behavioral

## Intent

Define a one-to-many dependency between objects so that when one object changes state (the Subject), all its dependents (the Observers) are notified and updated automatically.

## Applicability

* when an abstraction has two aspects, one dependent on the other
* when a change to one object requires changing others, and you don't know how many objects need to be changed
* when an object should notify other objects without making assumptions about who these objects are

## Consequences

* + modularity: subject and observers may vary independently
* + extensibility: can define and add any number of observers
* + customizability: different observers provide different views of subject
* - unexpected updates: observers don't know about each other
* - update overhead: might need hints

## Implementation

* subject-observer mapping
* dangling references
* avoiding observer-specific update protocols: the push and pull models
* registering modifications of interest explicitly

## Related pattern

* Singleton, is used to make observable object unique and accessible globally.
* Mediator, is used to encapsulate updated objects

## Description
### Problem

    In one place or many places in the application we need to be aware about a system event or an application state change. We'd like to have a standard way of subscribing to listening for system events and a standard way of notifying the interested parties. The notification should be automated after an interested party subscribed to the system event or application state change. There should be a way to unsubscribe, too.

### Forces

    Observers and observables probably should be represented by objects. The observer objects will be notified by the observable objects.

### Solution

    After subscribing the listening objects will be notified by a way of method call.

### Loose coupling

    When two objects are loosely coupled, they can interact, but they have very little knowledge of each other. Strive for loosely coupled designs between objects that interact.
* The only thing that Subject knows about an observer is that it implements a certain interface
* We can add new observers at any time
* We never need to modify the subject to add new types of observers
* We can reuse subjects or observers independently of each other
* Changes to either the subject or an observer will not affect the other

## Examples

The Observer pattern is used extensively in Java. E.g. in the following piece of code
* button is the Subject
* MyListener is the Observer
* actionPerformed is the equivalent to update
Another example is the PropertyChangeSupport. The Component class uses a PropertyChangeSupport object to let interested observers register for notification of changes in the properties of labels, panels, and other GUI components.
Can you find the Subject, Observer and update in the above class diagram?
* Component is the Subject
* PropertyChangeListener is the Observer
* propertyChange is the equivalent to update

## Cost

This pattern can be tricky if you do not beware. Beware the data representing the state changes of the subject can evolve without changing the interfaces. If you only transmit a string, the pattern could become very expensive if at least one new observer needs also a state code. You should use a mediator unless you know the implementation of the subject state will never change.

### Creation

This pattern has a cost to create.

### Maintenance

This pattern can be expensive to maintain.

### Removal

This pattern has a cost to remove too.

## Advises

* Put the subject and observer term in the name of the subject and the observer classes to indicate the use of the pattern to the other developers.
* To improve performances, you can only send to the observers the difference of states instead of the new state. The observers can only update following the changed part of the subject instead of all the state of the subject.

## Traditional Method

C# and the other .NET Framework languages do not typically require a full implementation of the Observer pattern using interfaces and concrete objects. Here is an example of using them, however.

## Using Events

The alternative to using concrete and abstract observers and publishers in C# and other .NET Framework languages, such as Visual Basic, is to use events. The event model is supported via delegates that define the method signature that should be used to capture events. Consequently, delegates provide the mediation otherwise provided by the abstract observer, the methods themselves provide the concrete observer, the concrete subject is the class defining the event, and the subject is the event system built into the base class library. It is the preferred method of accomplishing the Observer pattern in.NET applications.

## Handy implementation

You can implement this pattern in Java like this:

## Built-in support

The Java JDK has several implementations of this pattern: application in Graphical User Interfaces such as in the AWT toolkit, Swing etc. In Swing, whenever a user clicks a button or adjusts a slider, many objects in the application may need to react to the change. Swing refers to interested clients (observers) as "listeners" and lets you register as many listeners as you like to be notified of a component's events.
MVC is more M(VC) in Swing, i.e. View and Controller are tightly coupled; Swing does not divide Views from Controllers. MVC supports n-tier development, i.e. loosely coupled layers (see below) that can change independently and that may even execute on different machines.
There is also a built-in support for the Observer pattern. All one has to do is extend java.util.Observable (the Subject) and tell it when to notify the java.util.Observer s. The API does the rest for you. You may use either push or pull style of updating your observers.
java.util.Observable is a class while java.util.Observer is an interface.
Note that you have to call setChanged so that the Observable code will broadcast the change. The notifyObservers method calls the update method of each registered observer. The update method is a requirement for implementers of the Observer Interface.

### Keyboard handling

Below is an example written in Java that takes keyboard input and treats each input line as an event. The example is built upon the library classes java.util.Observer and java.util.Observable. When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods - in our example, ResponseHandler.update(...).
The file MyApp.java contains a main method that might be used in order to run the code.
The Java implementation of the Observer pattern has pros and cons:
Pros
* It hides many of the details of the Observer pattern
* It can be used both pull and push ways.
Cons
* Because Observable is a class, you have to subclass it; you can’t add on the Observable behavior to an existing class that subclasses another superclass (fails the programming to interfaces principle). If you can’t subclass Observable, then use delegation, i.e. provide your class with an Observable object and have your class forward key method calls to it.
* Because setChanged is protected, you can’t favour composition over inheritance.
class STUDENT
class TEACHER
Class SUBJECT
Application
OUTPUT
First Subject
Second Subject
The observer pattern in Python:
The observer pattern can be implemented more succinctly in Python using function decorators.
In Ruby, use the standard Observable mixin. For documentation and an example, see http://www.ruby-doc.org/stdlib/libdoc/observer/rdoc/index.html

# Prototype

The prototype pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
* avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
* avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
To implement the pattern, declare an abstract base class that specifies a pure virtual clone method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone operation.
The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone method through some mechanism provided by another design pattern.

## Rules of thumb

Sometimes creational patterns overlap — there are cases when either Prototype or Abstract Factory would be appropriate. At other times they complement each other: Abstract Factory might store a set of Prototypes from which to clone and return product objects (GoF, p126). Abstract Factory, Builder, and Prototype can use Singleton in their implementations. (GoF, p81, 134). Abstract Factory classes are often implemented with Factory Methods (creation through inheritance), but they can be implemented using Prototype (creation through delegation). (GoF, p95)
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. (GoF, p136)
Prototype doesn't require subclassing, but it does require an "initialize" operation. Factory Method requires subclassing, but doesn't require initialization. (GoF, p116)
Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. (GoF, p126)
The rule of thumb could be that you would need to clone an Object when you want to create another Object at runtime that is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as their initial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object that holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone instead of new.

## Advices

* Put the prototype term in the name of the prototype classes to indicate the use of the pattern to the other developers.
* Only use an interface when it is necessary.

## Implementations

It specifies the kind of objects to create using a prototypical instance. Prototypes of new products are often built prior to full production, but in this example, the prototype is passive and does not participate in copying itself. The mitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.
The concrete type of object is created from its prototype. MemberwiseClone is used in the Clone method to create and return a copy of ConcreteFoo1 or ConcreteFoo2.
Another example:
Code output:
This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class creates a clone of it and returns it as prototype. The clone method has been used to clone the prototype when required.
Another example:
Code output:
Another example:
Let's write an occurrence browser class for a text. This class lists the occurrences of a word in a text. Such an object is expensive to create as the locations of the occurrences need an expensive process to find. So, to duplicate such an object, we use the prototype pattern:
(the search algorithm is not optimized; it is a basic algorithm to illustrate the pattern implementation)
This implementation uses the decorator pattern.
Output:

# Proxy

Control the access to an object.
The example creates first an interface against which the pattern creates the classes. This interface contains only one method to display the image, called displayImage, that has to be coded by all classes implementing it.
The proxy class ProxyImage is running on another system than the real image class itself and can represent the real image RealImage over there. The image information is accessed from the disk. Using the proxy pattern, the code of the ProxyImage avoids multiple loading of the image, accessing it from the other system in a memory-saving manner.
Output
Notes:
* A proxy may hide information about the real object to the client.
* A proxy may perform optimization like on demand loading.
* A proxy may do additional house-keeping job like audit tasks.
* Proxy design pattern is also known as surrogate design pattern.
Another example:
The program's output is:
Output
Usage
Output
The following Java example illustrates the "virtual proxy" pattern. The ProxyImage class is used to access a remote method.
The example creates first an interface against which the pattern creates the classes. This interface contains only one method to display the image, called displayImage, that has to be coded by all classes implementing it.
The proxy class ProxyImage is running on another system than the real image class itself and can represent the real image RealImage over there. The image information is accessed from the disk. Using the proxy pattern, the code of the ProxyImage avoids multiple loading of the image, accessing it from the other system in a memory-saving manner. The lazy loading demonstrated in this example is not part of the proxy pattern, but is merely an advantage made possible by the use of the proxy.
Output
Output
More advanced proxies involve the Proxy object, which can intercept and redefine fundamental operations such as accessing properties. The handler functions in this case are sometimes called traps.
Output
Output
Output

# Singleton

The term Singleton refers to an object that can be instantiated only once. Use the Singleton Design pattern if:
* You need global access to a resource, like logging ...
* You need only one instance of a utility class, do not want to create lots of objects.
In some applications, it is appropriate to enforce a single instance of an object, for example: window managers, print spoolers, database access, and filesystems.

## Refresh Java object creation

In programming languages like Java, you have to create an instance of an object type (commonly called a Class) to use it throughout the code. Let's take for example this code:
This can also be written in a single line to save space.
At times, you need more than one instance of the same object type. You can create multiple instances of the same object type. Take for instance:
Now that I have two instances of the same object type, I can use both dog and cat instances separately in my program. Any changes to dog would not effect the cat instance because both of them have been created in separate memory spaces. To see whether these objects actually are different we do something like this:
The code returns false because both the objects are different. Contrary to this behavior, the Singleton behaves differently. A Singleton object type can not be instantiated yet you can obtain an instance of the object type. Let us create a normal object using Java.
What we have done here is that we have created a class (object type) to identify our object. Within the braces of the class is a single method with the same name as that of the class (methods can be identified by the usage of parentheses at the end of their names). Methods that have the same name as that of the class and that do not have a return type are called Constructors in OOP syntax. To create an instance of the class, the code can not be much simpler.
Note that to encourage the instantiation of this object, the constructor is called. The constructor as in this case can be called outside the class paranthesis and into another class definition because it is declared a public accessor while creating the Constructor in the above example.

### Creating singleton object

Now we will create the Singleton object. You just have to change one thing to adhere to the Singleton design pattern: Make your Constructor's accessor private.
Notice the constructor's accessor. This time around it has been declared private. Just by changing it to private, you have applied a great change to your object type. Now you can not instantiate the object type. Go ahead try out the following code.
The code returns an error because private class members can not be accessed from outside the class itself and in another class. This way you have disabled the instantiation process for an object type. However, you have to find a way of obtaining an instance of the object type. Let's do some changes here.
The changes involve adding a static class field called object and a public static method that can be accessible outside the scope of the class by using the name of the Class. To see how we can obtain the instance, lets code:
This way you control the creation of objects derived from your class. But we have still not unearthed the final and interesting part of the whole process. Try getting multiple objects and see what happens.
Unlike multiple instances of normal object types, multiple instances of a Singleton are all actually the same object instance. To validate the concept in Java, we try:
The code returns true because both object declarations are actually referring to the same object. So, in summarizing the whole concept, a Singleton can be defined as an object that can not be instantiated more than once. Typically it is obtained using a static custom implementation.

## Singleton & Multi Threading

Java uses multi threading concept, to run/execute any program. Consider the class SingletonObject discussed above. Call to the method getInstance by more than one thread at any point of time might create two instances of SingletonObject thus defeating the whole purpose of creating the singleton pattern. To make singelton thread safe, we have three options: 1. Synchronize the method getInstance, which would look like:
Synchronizing the method guarantees that the method will never be called twice at the same time. The problem with the above code is that 'synchronization' is expensive. 'Synchronization' checks will occur every time the function is called. Therefore, the above code should not be the first option. 2. Another approach would be to create a singleton instance as shown below:
The above code will be much faster; once the singleton instance is created no synchronization is needed. It just returns the same instance reference. 3. Use static initialization block to create the instance. The JVM makes sure that the static block is executed once when the class is loaded.

## Examples

In Java, the class java.lang.Runtime is a singleton. Its constructor is protected and you can get an instance by calling the getRuntime method.

## Cost

Beware of this design pattern! It creates the same issues than the global variables in procedural programming so it can be hard to debug.

### Creation

It can be expensive. You may have to refactor all the instantiations of the class, unless the class is new.

### Maintenance

There is no additional cost.

### Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

## Advises

* Name the method getInstance to indicate the use of the pattern to the other developers.
* Use this design pattern for frozen data like configuration or external data. You will not have debugging issues.

## Implementation

The Scala programming language supports Singleton objects out-of-the-box. The 'object' keyword creates a class and also defines a singleton object of that type. Singletons are declared just like classes except "object" replaces the keyword "class".

## Traditional simple way using synchronization

This solution is thread-safe without requiring special language constructs:

## Initialization on Demand Holder Idiom

This technique is as lazy as possible, and works in all known versions of Java. It takes advantage of language guarantees about class initialization, and will therefore work correctly in all Java-compliant compilers and virtual machines. The nested class is referenced when getInstance is called making this solution thread-safe without requiring special language constructs.

## The Enum-way

In the second edition of his book "Effective Java" Joshua Bloch claims that "a single-element enum type is the best way to implement a singleton" for any Java that supports enums. The use of an enum is very easy to implement and has no drawbacks regarding serializable objects, which have to be circumvented in the other ways.
Singleton pattern in D programming language
Or in this manner
Singleton pattern in PHP 5:
Private constructors are not available in ActionScript 3.0 - which prevents the use of the ActionScript 2.0 approach to the Singleton Pattern. Many different AS3 Singleton implementations have been published around the web.
A common way to implement a singleton in Objective-C is the following:
If thread-safety is not required, the synchronization can be left out, leaving the +sharedSingleton method like this:
This pattern is widely used in the Cocoa frameworks (see for instance, NSApplication, NSColorPanel, NSFontPanel or NSWorkspace, to name but a few). Some may argue that this is not, strictly speaking, a Singleton, because it is possible to allocate more than one instance of the object. A common way around this is to use assertions or exceptions to prevent this double allocation.
There are alternative ways to express the Singleton pattern in Objective-C, but they are not always as simple or as easily understood, not least because they may rely on the -init method returning an object other than self. Some of the Cocoa "Class Clusters" (e.g. NSString, NSNumber) are known to exhibit this type of behaviour. Note that @synchronized is not available in some Objective-C configurations, as it relies on the NeXT/Apple runtime. It is also comparatively slow, because it has to look up the lock based on the object in parentheses.
The simplest of all is:
This example is thread-safe with lazy initialization.
Example in C# 2.0 (thread-safe with lazy initialization) Note: This is not a recommended implementation because "TestClass" has a default public constructor, and that violates the definition of a Singleton. A proper Singleton must never be instantiable more than once. More about generic singleton solution in C#: http://www.c-sharpcorner.com/UploadFile/snorrebaard/GenericSingleton11172008110419AM/GenericSingleton.aspx
As described by James Heyworth in a paper presented to the Canberra PC Users Group Delphi SIG on 11/11/1996, there are several examples of the Singleton pattern built into the Delphi Visual Component Library. This unit demonstrates the techniques that were used in order to create both a Singleton component and a Singleton object:
The desired properties of the Singleton pattern can most simply be encapsulated in Python by defining a module, containing module-level variables and functions. To use this modular Singleton, client code merely imports the module to access its attributes and functions in the normal manner. This sidesteps many of the wrinkles in the explicitly-coded versions below, and has the singular advantage of requiring zero lines of code to implement. According to influential Python programmer Alex Martelli, The Singleton design pattern (DP) has a catchy name, but the wrong focus—on identity rather than on state. The Borg design pattern has all instances share state instead. A rough consensus in the Python community is that sharing state among instances is more elegant, at least in Python, than is caching creation of identical instances on class initialization. Coding shared state is nearly transparent:
But with the new style class, this is a better solution, because only one instance is created:
Two caveats:
* The __init__-method is called every time Singleton is called, unless cls.__init__ is set to an empty function.
* If it is needed to inherit from the Singleton-class, instance should probably be a dictionary belonging explicitly to the Singleton-class.
To create a singleton that inherits from a non-singleton, multiple inheritance must be used.
Be sure to call the NonSingletonClass's __init__ function from the Singleton's __init__ function. A more elegant approach using metaclasses was also suggested.
In Perl version 5.10 or newer a state variable can be used.
In older Perls, just use a global variable.
If Moose is used, there is the MooseX::Singleton extension module.
In Ruby, just include the Singleton module from the standard library into the class.
In ABAP Objects, to make instantiation private, add an attribute of type ref to the class, and a static method to control instantiation.

# State

Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class.
The state interface and two implementations. The state's method has a reference to the context object and is able to change its state.
The context class has a state variable that it instantiates in an initial state, in this case StateA. In its method, it uses the corresponding methods of the state object.
The test below shows also the usage:
According to the above code, the output of main from TestClientState should be:
According to the above Perl and Python code, the output of main should be:
In the Ruby example below, a radio can switch to two states AM and FM and has a scan button to switch to the next station.
The state interface and two implementations. The state's method has a reference to the context object and is able to change its state.
The context class has a state variable that it instantiates in an initial state, in this case StateA. In its method, it uses the corresponding methods of the state object.
The test below shows also the usage:
According to the above code, the output of main entry point should be:

## References

* ↑ "Proxy - JavaScript | MDN". developer.mozilla.org. Retrieved 21 January 2022.
* ↑ revised from http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

# Strategy
## Scope

Object

## Purpose

Behavioral

## Intent

Define a family of algorithms, encapsulate each one, and make them interchangeable to let clients and algorithms vary independently from the clients using it.

## Applicability

* when an object should be configurable with one of several algorithms,
* and all algorithms can be encapsulated,
* and one interface covers all encapsulations

## Consequences

* + greater flexibility, reuse
* + can change algorithms dynamically
* - strategy creation & communication overhead
* - inflexible Strategy interface

## Implementation

* exchanging information between a Strategy and its context
* static strategy selection via templates

## Related patterns

* State, can activate several states, whereas a strategy can only activate one of the algorithms.
* Flyweight, provides a shared object that can be used in multiple contexts simultaneously, whereas a strategy focuses on one context.
* Decorator, changes the skin of an object, whereas a strategy changes the guts of an object.
* Composite, is used in combination with a strategy to improve efficiency.

## Description

Suppose that you work for a company that builds a strategy game. Let's assume that you've come up with the following hierarchy of classes. All characters are able to walk, and there is also a method to render them on screen. The superclass takes care of the implementation of walk method, while each subclass provides its own implementation of display since each character looks different.
A new requirement arrives that the characters need to fight, too. Simple job you say; just add a fight method to Character superclass. But, wait a moment; what about Workers? They cannot fight!
Well, one could think that you could simply override fight method in Worker subclass to just do nothing.
But what if in the future there is a need for a Guard class that can fight but shouldn’t walk? We need a cleaner solution. What about taking out the fight and walk behaviors from the superclass to an interface? That way, only the characters that are supposed to walk should implement the Walkable interface and only those characters that are supposed to fight should implement the Fightable interface.
Well, this is another way to say for duplicate code. What if you need to make a small change to the fight behavior? You would need to modify all the classes. At this point we should put down three design principles to follow in our application development:
* Identify the aspects of your application that vary and separate them from what stays the same. Take what varies and “encapsulate” it so it won’t affect the rest of your code.
* Program to an interface not to an implementation.
* Favour composition over inheritance.
So, let's apply the 1st design principle. Pull out fight and walk behavior to different classes. And to apply the 2nd design principle as well, we have to pull out these behaviors to interfaces. Hence, we create a new WeaponBehavior interface to deal with fight behavior, and similarly a WalkBehavior interface to deal with walk behavior.
Characters’ behaviors live in separate classes that implement a particular behavior interface. That way, the Character classes don’t need to know any of the implementation details for their own behaviors. In addition, we no more rely on an implementation but on an interface. Other types of objects can use these behaviors, too, because they're not hidden inside our Character class. And we can add new behaviors without modifying any of the existing ones or touching our character classes. So now, all we have to do is have our Character class delegate all behavior information to the two behavior interfaces (so here comes the 3rd design principle). We do that by adding two instance variables to Character, weapon and walk.
Each character object will set these variables polymorphically to reference the specific behavior type it would like at runtime.
Think of these behaviors as families of algorithms. So, composition gives you a lot of flexibility. Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also lets you change behavior at runtime as long as the object you are composing with, implements the correct behavior interface.

## Cost

Think twice before implementing this pattern. You have to be sure your need is to frequently change an algorithm. You have to clearly anticipate the future, otherwise, this pattern will be more expensive than a basic implementation.

### Creation

This pattern is expensive to create.

### Maintenance

This pattern can be expensive to maintain. If the representation of a class often changes, you will have lots of refactoring.

### Removal

This pattern is hard to remove too.

## Advises

* Use the strategy term to indicate the use of the pattern to the other developers.

## Implementations

The strategy pattern in ActionScript 3:
A struct in C can be used to define a class, and the strategy can be set using a function pointer. The following mirrors the Python example, and uses C99 features:
The strategy pattern in C++ is similar to Java, but does not require dynamic allocation of objects.
Another Example:
Delegates in C# follow the strategy pattern, where the delegate definition defines the strategy interface and the delegate instance represents the concrete strategy. .NET 3.5 defines the Func<,> delegate which can be used to quickly implement the strategy pattern as shown in the example below. Note the 3 different methods for defining a delegate instance.

### Using interfaces

An example in Common Lisp: Using strategy classes:
In Common Lisp using first class functions:
Similar to Python and Scala, Falcon supports first-class functions. The following implements the basic functionality seen in the Python example.
Fortran 2003 adds procedure pointers, abstract interfaces and also first-class functions. The following mirrors the Python example.
This Groovy example is a basic port of the Ruby using blocks example. In place of Ruby's blocks, the example uses Groovy's closure support.
An example in Java:
An example in Java:
Similar to Python and Scala, JavaScript supports first-class functions. The following implements the basic functionality seen in the Python example.
Perl has first-class functions, so as with Python, JavaScript and Scala, this pattern can be implemented without defining explicit subclasses and interfaces:
The strategy pattern can be formally implemented with Moose:
The strategy pattern in PHP:
PowerShell has first-class functions called ScriptBlocks, so the pattern can be modeled like Python, passing the function directly to the context instead of defining a class.
An alternative to using New-Module
The following example is equivalent to the C# example 1 above, but in Python.
Second example in Python:
Another example in Python: Python has first-class functions, so the pattern can be used simply by passing the function directly to the context instead of defining a class with a method containing the function. One loses information because the interface of the strategy is not made explicit, however, by simplifying the pattern in this manner.
Here's an example you might encounter in GUI programming, using a callback function:
An example in Ruby:

### Using blocks

The previous ruby example uses typical OO features, but the same effect can be accomplished with ruby's blocks in much less code.
Like Python, Scala also supports first-class functions. The following implements the basic functionality shown in the Python example.

# Template method

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of algorithm without changing the algorithm's structure.

# Visitor

The visitor pattern allows you to easily perform a given operation (function, algorithm, etc…) on each element of a complex structure. The benefit is that you can easily add other operations to perform and you can easily change the structure of the elements. The principle is that the classes that are used to perform the operations and the classes that scroll the structures are different. It also means that, if you know that you will always have only one operation to perform on the structure, this pattern is useless.
Let's take the simple data class:
We want to perform an operation on it. Instead of implementing it inside of the class, we will use a visitor class. A visitor class is a class that performs an action on an object. It will perform an action on a whole structure by being called for each element. However, for now, we only have one object. The visitor will be called by the visit method by the data object, and the object will be called by the accept method by the client:
* <<interface>> Visitor
* +visit(Element)
* <<interface>> Element
* +accept(Visitor)
* ConcreteVisitor
* +visit(Element)
* ConcreteElement
* +accept(Visitor)
Then you can define a structure of data object and each object will call the accept method on its sub-elements. You may think that the main drawback of this pattern is that even if the visitor can process all the elements, it does not process it as a whole, i.e. it can't connect the different elements together, so the pattern is limited. Not at all. The visitor can keep information about the elements it has already visited (for example to log lines with appropriate indentation). If the visitor needs information from all the elements (for example to compute a percentage based on the sum), it can visit all the elements, store information, and actually process all the information after the last visit using another method. In other words, you can add states to your visitor.
This process is essentially equivalent to getting the collection's iterator, and using a while(iterator.hasNext) loop to invoke visitor.visit(iterator.next). The key difference is that the collection can decide exactly how to step through the elements. If you're familiar with iterators, you may be thinking that the iterator can decide how to step through, too, and the iterator is usually defined by the collection, so what's the difference? The difference is that the iterator is still bound to a while loop, visiting each element in succession, one at a time. With the visitor pattern, the collection could conceivably create a separate thread for each element and have the visitor visiting them concurrently. That's just one example of ways that the collection may decide to vary the method of visitation in a manner that can't be mimicked by an iterator. The point is, it's encapsulated, and the collection can implement the pattern in whatever way it feels is best. More importantly, it can change the implementation at any time, without affecting client code, because the implementation is encapsulated in the foreach method.

## An example implementation of Visitor Pattern: String

To illustrate the visitor pattern, let's imagine we're reinventing Java's String class (it'll be a pretty ridiculous reinvention, but it'll be good for this exercise). We're not going to implement very much of the class, but let's assume that we're storing a set of chars that make up the string, and we have a method called getCharAt that takes an int as its only argument, and returns the character at that position in the string, as a char. We also have a method called length that takes no arguments, and returns an int that gives the number of characters in the string. Let's also assume that we want to provide an implementation of the visitor pattern for this class that will take an instance that implements the ICharacterVisitor interface (that we'll define, below), and calls its visit method for each character in the string. First we need to define what this ICharacterVisitor interface looks like:
Easy enough. Now, let's get down to our class, which we'll call MyString, and it looks something like this:
So, that was pretty painless. What can we do with this? Well, let's make a class called MyStringPrinter, which prints an instance of MyString to the standard output.
That was simple too. Of course, it could've been a lot simpler, right? We didn't need the foreach method in MyString, and we didn't need MyStringPrinter to implement the visitor, we could have just used the MyString classes getCharAt and length methods to set up our own for loop ourselves and printed each char inside the loop. Well, sure you could, but what if MyString isn't MyString but instead is MyBoxOfRocks.

## Another example implementation of Visitor Pattern: Rock

In a box of rocks, is there a set order that the rocks are in? Unlikely. Of course MyBoxOfRocks has to store the rocks somehow. Maybe, it stores them in an array, and there is actually a set order of the rocks, even if it is artificially introduced for the sake of storage. On the other hand, maybe it doesn't. The point is once again that it is an implementation detail that you as the client of MyBoxOfRocks shouldn't have to worry about, and should never rely on.
Presumably, MyBoxOfRocks wants to provide someway for clients to get to the rocks inside it. It could, once again, introduce an artificial order to the rocks; assign each rock an index and provide a method like public Rock getRock(int aRockNumber). Or maybe it wants to put names on all the rocks and let you access it like public Rock getRock(String aRockName). But maybe it's really just a box of rocks, and there are no names, no numbers, no way of identifying which rock you want; all you know is you want the rocks. Alright, let's try it with the visitor pattern. First, our visitor interface (assume Rock is already defined somewhere, we don't care what it is or what it does):
Easy. Now out MyBoxOfRocks
Huh, what do you know, it does store them in an array. But what do we care now? We already wrote the visitor interface, and all we have to do now is implement it in some class that defines the actions to take for each rock, which we would have to do inside a for loop anyway. Besides, the array is private, our visitor doesn't have any access to that.
And what if the implementor of MyBoxOfRocks did a little homework and found out that comparing a number to zero is infinitesimally faster than comparing it to a non-zero value? Infinitesimal, sure, but maybe when you're iterating over 10 million rocks, it makes a difference (maybe!). So, he decides to change the implementation:
Now, he's iterating backwards through the array and saving a (very) little time. He's changed the implementation because he found a better way. You didn't have to worry about finding the best way, and you didn't have to change your code because the implementation is encapsulated. And that's not the half of it. Maybe, a new coder takes control of the project, and maybe this coder hates arrays and decides to totally change it:
Now, maybe in this instance, linked lists were a poor idea, not as fast as a nice lean array and a for loop. On the other hand, you don't know what else this class is supposed to do. Maybe, providing access to the rocks is only a small part of what it does, and linked lists fit in better with the rest of the requirements. In case I haven't said it enough yet, the point is that you as the client of MyBoxOfRocks don't have to worry about changes to the implementation, the visitor pattern protects you from it.
I have one more trick up my sleeve. Maybe, the implementor of MyBoxOfRocks notices that a lot of visitors are taking a really long time to visit each rock, and it's taking far too long for the foreach method to return because it has to wait for all visitors to finish. He decides it can't wait that long, and he also decides that some of these operations can probably be going on all at once. So, he decides to do something about it, namely, this:
If you're familiar with threads, you'll understand what's going on here. If you're not, I'll quickly summarize: a Thread is basically something that can run "simultaneously" with other threads on the same machine. They don't actually run simultaneously of course, unless maybe you have a multi-processor machine, but as far as Java is concerned, they do. So, for instance, when we created this new Thread called t, and defined what happens when the Thread is run (with the run method, naturally), we can then start the Thread, and it will start running, splitting cycles on the processor with other Threads, right away, doesn't have to wait for the current method to return. Likewise, we can start it running and then continue on our own way immediately, without waiting for it to return. So, with the above implementation, the only time we need to spend in this method is the time it takes to instantiate all the threads, start them running, and loop over the array; we don't have to wait for the visitor to actually visit each Rock before we can loop, we just loop right away, and the visitor does its thing on whatever CPU cycles it can swipe. The whole visiting process might take a long time – maybe even longer, if it looses some cycles because of the multiple threads, but the thread from which foreach was invoked doesn't have to wait for it to finish: it can return from the method and be on it's way much faster.
If you're confused about the use of the final Rock called "current" in the above code, it's just a bit of technicality using anonymous classes: they can't access non-final local variables. Even though fRocks doesn't fit into this category (it's not local, but an instance variable), i does. If you tried to remove this line and simply put fRocks[i] in the run method, it wouldn't compile.
So, what happens if you're the visitor, and you decide that you need to visit each rock one at a time? There's a number of reasons this might happen such as, if your visit method changes your instance variables, or it depends on the results of previous calls of visit. Well, the implementation inside the foreach method is encapsulated, so you don't know if it's using separate threads or not. Sure, you could figure it out with some fancy debugging, or some clever printing to std out, but wouldn't it be nice, if you didn't have to? And if you could be sure that, if they change it in the next version, your code will still work properly? Well, fortunately, Java provides the synchronize mechanism, which is basically an elaborate device for locking up blocks of code so that only one Thread can access them at a time. This won't conflict with the interests of the multi-threaded implementation either, because the locked-out thread still won't block the thread that created them, but they will just sit and wait patiently, only blocking code on itself. That's all well beyond the scope of this section, however, but be aware that it's available and probably worth looking into, if you're going to be using synchronicity-sensitive visitors.

## Cost

This pattern is flexible enough not to block you. At worst, you will need to spend time thinking about how to solve problems, but this pattern will never block you.

### Creation

This pattern is expensive to create, if your code already exists.

### Maintenance

It is easy to adapt the code with this pattern, even if there are new links between the item visits.

### Removal

This pattern can be removed using refactoring operations from your IDE.

## Advises

* Use the visitor and visit term to indicate the use of the pattern to the other developers.
* If you have and will always have only one visitor, you'd rather implement the composite pattern.

## Implementations

The following example is an example in the C# programming language:
The following example is in the D programming language:
The following example is in the Java programming language:
The following example is an example in the Scala programming language:
Output: