<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Sskanitk</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Sskanitk"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Sskanitk"/>
	<updated>2026-06-06T07:36:50Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54136</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54136"/>
		<updated>2011-10-23T21:41:15Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Coding Example - Adapter Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists of numerous examples. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''''1. SINGLETON PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
# You might want to have only one Window Manager to manage all your open windows in your system.&lt;br /&gt;
# Logging, where it provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. &amp;lt;ref&amp;gt;[http://www.oodesign.com/singleton-pattern.html Logger Classes]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''2. ADAPTER PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. - Head First Design Patterns &amp;lt;ref&amp;gt;[Freeman, Elisabeth, Bert Bates, and Kathy Sierra. Head First Design Patterns. Web.]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not based on if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
==='''''3. COMMAND PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns &amp;lt;ref&amp;gt;[Freeman, Elisabeth, Bert Bates, and Kathy Sierra. Head First Design Patterns. Web.]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''4. STRATEGY PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;In computer programming, the strategy pattern is a design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&amp;quot; - Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Strategy_pattern Stratey Pattern Wikipedia]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example code for Strategy pattern====&lt;br /&gt;
Here we will see how strategy pattern can be used to sort a given list of real numbers using either BubbleSort() or QuickSort().&lt;br /&gt;
&lt;br /&gt;
Below is an interface to describe the individual algorithms.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public interface SortingInterface {&lt;br /&gt;
      public void sort(double[] list);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now implement both the Quicksort &amp;amp; Bubblesort strategies.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class QuickSort implements SortingInterface {&lt;br /&gt;
      //QuickSort will implement the sort() with the quicksort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
             //Do quick sort here&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
public class BubbleSort implements SortingInterface {&lt;br /&gt;
      &lt;br /&gt;
      //BubbleSort will implement the sort() with the bubblesort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
            //Do bubble sort here  &lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now define a Strategy context that maintains a reference to a Strategy object(Bubblesort or Quicksort) and forwards client requests to that strategy.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Context {&lt;br /&gt;
private SortingInterface algorithm = null;&lt;br /&gt;
&lt;br /&gt;
public void sortGivenList(double[] list) {&lt;br /&gt;
       algorithm.sort(list);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Getter method for algorithm&lt;br /&gt;
public SortingInterface getAlgorithm() {&lt;br /&gt;
       return algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Setter method for algorithm&lt;br /&gt;
public void setAlgorithm(SortingInterface algorithm) {&lt;br /&gt;
       this.algorithm = algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the client picks one of the available strategies(Quicksort or Bubblesort) in the context and sorts the List according to that strategy as shown below.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
      &lt;br /&gt;
      //Here is the List&lt;br /&gt;
      double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};&lt;br /&gt;
&lt;br /&gt;
      //Now define the Context&lt;br /&gt;
      Context context = new Context();&lt;br /&gt;
&lt;br /&gt;
      //Now pick your strategy i.e. Quicksort or Bubblesort&lt;br /&gt;
      context.setAlgorithm(new BubbleSort());&lt;br /&gt;
&lt;br /&gt;
      ///Now, sort it using the strategy you picked&lt;br /&gt;
      context.sortGivenList(list);&lt;br /&gt;
      &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
*Sorting a list: where the strategy can be to choose the sorting algorithm itself (QuickSort, HeapSort, etc.) at runtime depending on the input data. &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Sorting a llist using Strategy pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Layout_manager Layout Managers] in UI toolkits: where you can decide at runtime what layout is to be chosen for the GUI to be displayed.&amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern Strategy Pattern Real world examples]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Differences between Command and Strategy Pattern====&lt;br /&gt;
*A Command Pattern encapsulates a single action/algorithm whereas the Strategy pattern provides us with a number of actions/algorithms which can be selected based on a number of factors.&lt;br /&gt;
*A Command Pattern object has a single method but with a generic signature whereas Strategy pattern may have as many different methods provided.&lt;br /&gt;
&lt;br /&gt;
==Design Patterns at a Glance==&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Design Patterns&lt;br /&gt;
! Singleton&lt;br /&gt;
! Adapter&lt;br /&gt;
! Command&lt;br /&gt;
! Strategy&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Purpose&lt;br /&gt;
| To ensure a class has only one instance, and also to provide a global point of access to it&lt;br /&gt;
| To convert the interface of a class into another interface the clients expects&lt;br /&gt;
| To encapsulate method invocations so as to decouple caller from the implementation details&lt;br /&gt;
| To perform a bunch of different things to do, based on the situation/context&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Advantages&lt;br /&gt;
| Sane usage of global namespace by avoiding unnecessary global variables and providing on-demand (lazy) instantiations.&lt;br /&gt;
| It lets classes work together that could not otherwise because of incompatible interfaces.&lt;br /&gt;
| It allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
| It lets the algorithms vary independently from clients that use those.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Disadvantages&lt;br /&gt;
| Introduces global state into system and complicates unit testing.&lt;br /&gt;
| Adapter has to implement the entire target interface. Selective functionality implementation is not an option.&lt;br /&gt;
| Having Command objects specific to each action ends up cluttering the design, especially in the context of MVC architectures &amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Disadvantage of Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
| Increases the number of objects and all algorithms use the same interface. &amp;lt;ref&amp;gt; [https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Disadvantages of Strategy Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
*The objective of the Singleton pattern as defined in Design Patterns is to &amp;quot;ensure a class has only one instance, and  also to provide a global point of access to it&amp;quot;.&amp;lt;ref&amp;gt;[http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/b746fa87-5e52-4474-b5f7-688c7f14823c Why or Why not Singleton]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Adapter Pattern converts the interface of a class into another interface the clients expects. This decouples the client and adaptee and allows them to work together.&lt;br /&gt;
* Command Pattern encapsulates method invocations, by which pieces of computation are crystallized, hence the object invoking the computation doesn't need to worry about how things are done.&lt;br /&gt;
*Strategy pattern should be used when you have a bunch of different things to do, based on the situation/context.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==External Resources==&lt;br /&gt;
*Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Web. &lt;br /&gt;
*Effective Java 2nd Edition By Joshua Bloch&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54135</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54135"/>
		<updated>2011-10-23T21:39:02Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Examples */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists of numerous examples. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''''1. SINGLETON PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
# You might want to have only one Window Manager to manage all your open windows in your system.&lt;br /&gt;
# Logging, where it provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. &amp;lt;ref&amp;gt;[http://www.oodesign.com/singleton-pattern.html Logger Classes]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''2. ADAPTER PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. - Head First Design Patterns &amp;lt;ref&amp;gt;[Freeman, Elisabeth, Bert Bates, and Kathy Sierra. Head First Design Patterns. Web.]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
==='''''3. COMMAND PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns &amp;lt;ref&amp;gt;[Freeman, Elisabeth, Bert Bates, and Kathy Sierra. Head First Design Patterns. Web.]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''4. STRATEGY PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;In computer programming, the strategy pattern is a design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&amp;quot; - Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Strategy_pattern Stratey Pattern Wikipedia]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example code for Strategy pattern====&lt;br /&gt;
Here we will see how strategy pattern can be used to sort a given list of real numbers using either BubbleSort() or QuickSort().&lt;br /&gt;
&lt;br /&gt;
Below is an interface to describe the individual algorithms.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public interface SortingInterface {&lt;br /&gt;
      public void sort(double[] list);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now implement both the Quicksort &amp;amp; Bubblesort strategies.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class QuickSort implements SortingInterface {&lt;br /&gt;
      //QuickSort will implement the sort() with the quicksort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
             //Do quick sort here&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
public class BubbleSort implements SortingInterface {&lt;br /&gt;
      &lt;br /&gt;
      //BubbleSort will implement the sort() with the bubblesort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
            //Do bubble sort here  &lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now define a Strategy context that maintains a reference to a Strategy object(Bubblesort or Quicksort) and forwards client requests to that strategy.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Context {&lt;br /&gt;
private SortingInterface algorithm = null;&lt;br /&gt;
&lt;br /&gt;
public void sortGivenList(double[] list) {&lt;br /&gt;
       algorithm.sort(list);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Getter method for algorithm&lt;br /&gt;
public SortingInterface getAlgorithm() {&lt;br /&gt;
       return algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Setter method for algorithm&lt;br /&gt;
public void setAlgorithm(SortingInterface algorithm) {&lt;br /&gt;
       this.algorithm = algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the client picks one of the available strategies(Quicksort or Bubblesort) in the context and sorts the List according to that strategy as shown below.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
      &lt;br /&gt;
      //Here is the List&lt;br /&gt;
      double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};&lt;br /&gt;
&lt;br /&gt;
      //Now define the Context&lt;br /&gt;
      Context context = new Context();&lt;br /&gt;
&lt;br /&gt;
      //Now pick your strategy i.e. Quicksort or Bubblesort&lt;br /&gt;
      context.setAlgorithm(new BubbleSort());&lt;br /&gt;
&lt;br /&gt;
      ///Now, sort it using the strategy you picked&lt;br /&gt;
      context.sortGivenList(list);&lt;br /&gt;
      &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
*Sorting a list: where the strategy can be to choose the sorting algorithm itself (QuickSort, HeapSort, etc.) at runtime depending on the input data. &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Sorting a llist using Strategy pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Layout_manager Layout Managers] in UI toolkits: where you can decide at runtime what layout is to be chosen for the GUI to be displayed.&amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern Strategy Pattern Real world examples]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Differences between Command and Strategy Pattern====&lt;br /&gt;
*A Command Pattern encapsulates a single action/algorithm whereas the Strategy pattern provides us with a number of actions/algorithms which can be selected based on a number of factors.&lt;br /&gt;
*A Command Pattern object has a single method but with a generic signature whereas Strategy pattern may have as many different methods provided.&lt;br /&gt;
&lt;br /&gt;
==Design Patterns at a Glance==&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Design Patterns&lt;br /&gt;
! Singleton&lt;br /&gt;
! Adapter&lt;br /&gt;
! Command&lt;br /&gt;
! Strategy&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Purpose&lt;br /&gt;
| To ensure a class has only one instance, and also to provide a global point of access to it&lt;br /&gt;
| To convert the interface of a class into another interface the clients expects&lt;br /&gt;
| To encapsulate method invocations so as to decouple caller from the implementation details&lt;br /&gt;
| To perform a bunch of different things to do, based on the situation/context&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Advantages&lt;br /&gt;
| Sane usage of global namespace by avoiding unnecessary global variables and providing on-demand (lazy) instantiations.&lt;br /&gt;
| It lets classes work together that could not otherwise because of incompatible interfaces.&lt;br /&gt;
| It allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
| It lets the algorithms vary independently from clients that use those.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Disadvantages&lt;br /&gt;
| Introduces global state into system and complicates unit testing.&lt;br /&gt;
| Adapter has to implement the entire target interface. Selective functionality implementation is not an option.&lt;br /&gt;
| Having Command objects specific to each action ends up cluttering the design, especially in the context of MVC architectures &amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Disadvantage of Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
| Increases the number of objects and all algorithms use the same interface. &amp;lt;ref&amp;gt; [https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Disadvantages of Strategy Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
*The objective of the Singleton pattern as defined in Design Patterns is to &amp;quot;ensure a class has only one instance, and  also to provide a global point of access to it&amp;quot;.&amp;lt;ref&amp;gt;[http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/b746fa87-5e52-4474-b5f7-688c7f14823c Why or Why not Singleton]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Adapter Pattern converts the interface of a class into another interface the clients expects. This decouples the client and adaptee and allows them to work together.&lt;br /&gt;
* Command Pattern encapsulates method invocations, by which pieces of computation are crystallized, hence the object invoking the computation doesn't need to worry about how things are done.&lt;br /&gt;
*Strategy pattern should be used when you have a bunch of different things to do, based on the situation/context.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==External Resources==&lt;br /&gt;
*Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Web. &lt;br /&gt;
*Effective Java 2nd Edition By Joshua Bloch&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54057</id>
		<title>Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54057"/>
		<updated>2011-10-21T19:40:35Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Design Patterns at a Glance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page has been moved to [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54052</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54052"/>
		<updated>2011-10-21T19:36:10Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''''1. SINGLETON PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
# You might want to have only one Window Manager to manage all your open windows in your system.&lt;br /&gt;
# Logging, where it provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. &amp;lt;ref&amp;gt;[http://www.oodesign.com/singleton-pattern.html Logger Classes]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''2. ADAPTER PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
==='''''3. COMMAND PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''4. STRATEGY PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;In computer programming, the strategy pattern is a design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&amp;quot; - Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Strategy_pattern Stratey Pattern Wikipedia]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example code for Strategy pattern====&lt;br /&gt;
Here we will see how strategy pattern can be used to sort a given list of real numbers using either BubbleSort() or QuickSort().&lt;br /&gt;
&lt;br /&gt;
Below is an interface to describe the individual algorithms.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public interface SortingInterface {&lt;br /&gt;
      public void sort(double[] list);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now implement both the Quicksort &amp;amp; Bubblesort strategies.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class QuickSort implements SortingInterface {&lt;br /&gt;
      //QuickSort will implement the sort() with the quicksort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
             //Do quick sort here&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
public class BubbleSort implements SortingInterface {&lt;br /&gt;
      &lt;br /&gt;
      //BubbleSort will implement the sort() with the bubblesort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
            //Do bubble sort here  &lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now define a Strategy context that maintains a reference to a Strategy object(Bubblesort or Quicksort) and forwards client requests to that strategy.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Context {&lt;br /&gt;
private SortingInterface algorithm = null;&lt;br /&gt;
&lt;br /&gt;
public void sortGivenList(double[] list) {&lt;br /&gt;
       algorithm.sort(list);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Getter method for algorithm&lt;br /&gt;
public SortingInterface getAlgorithm() {&lt;br /&gt;
       return algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Setter method for algorithm&lt;br /&gt;
public void setAlgorithm(SortingInterface algorithm) {&lt;br /&gt;
       this.algorithm = algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the client picks one of the available strategies(Quicksort or Bubblesort) in the context and sorts the List according to that strategy as shown below.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
      &lt;br /&gt;
      //Here is the List&lt;br /&gt;
      double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};&lt;br /&gt;
&lt;br /&gt;
      //Now define the Context&lt;br /&gt;
      Context context = new Context();&lt;br /&gt;
&lt;br /&gt;
      //Now pick your strategy i.e. Quicksort or Bubblesort&lt;br /&gt;
      context.setAlgorithm(new BubbleSort());&lt;br /&gt;
&lt;br /&gt;
      ///Now, sort it using the strategy you picked&lt;br /&gt;
      context.sortGivenList(list);&lt;br /&gt;
      &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
*Sorting a list: where the strategy can be to choose the sorting algorithm itself (QuickSort, HeapSort, etc.) at runtime depending on the input data. &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Sorting a llist using Strategy pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Layout_manager Layout Managers] in UI toolkits: where you can decide at runtime what layout is to be chosen for the GUI to be displayed.&amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern Strategy Pattern Real world examples]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Differences between Command and Strategy Pattern====&lt;br /&gt;
*A Command Pattern encapsulates a single action/algorithm whereas the Strategy pattern provides us with a number of actions/algorithms which can be selected based on a number of factors.&lt;br /&gt;
*A Command Pattern object has a single method but with a generic signature whereas Strategy pattern may have as many different methods provided.&lt;br /&gt;
&lt;br /&gt;
==Design Patterns at a Glance==&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Design Patterns&lt;br /&gt;
! Singleton&lt;br /&gt;
! Adapter&lt;br /&gt;
! Command&lt;br /&gt;
! Strategy&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Purpose&lt;br /&gt;
| To ensure a class has only one instance, and also to provide a global point of access to it&lt;br /&gt;
| To convert the interface of a class into another interface the clients expects&lt;br /&gt;
| To encapsulate method invocations so as to decouple caller from the implementation details&lt;br /&gt;
| To perform a bunch of different things to do, based on the situation/context&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Advantages&lt;br /&gt;
| Sane usage of global namespace by avoiding unnecessary global variables and providing on-demand (lazy) instantiations.&lt;br /&gt;
| It lets classes work together that could not otherwise because of incompatible interfaces.&lt;br /&gt;
| It allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
| It lets the algorithms vary independently from clients that use those.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Disadvantages&lt;br /&gt;
| Introduces global state into system and complicates unit testing.&lt;br /&gt;
| Adapter has to implement the entire target interface. Selective functionality implementation is not an option.&lt;br /&gt;
| Having Command objects specific to each action ends up cluttering the design, especially in the context of MVC architectures &amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Disadvantage of Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
| Increases the number of objects and all algorithms use the same interface. &amp;lt;ref&amp;gt; [https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Disadvantages of Strategy Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
*The objective of the Singleton pattern as defined in Design Patterns is to &amp;quot;ensure a class has only one instance, and  also to provide a global point of access to it&amp;quot;.&amp;lt;ref&amp;gt;[http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/b746fa87-5e52-4474-b5f7-688c7f14823c Why or Why not Singleton]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Adapter Pattern converts the interface of a class into another interface the clients expects. This decouples the client and adaptee and allows them to work together.&lt;br /&gt;
* Command Pattern encapsulates method invocations, by which pieces of computation are crystallized, hence the object invoking the computation doesn't need to worry about how things are done.&lt;br /&gt;
*Strategy pattern should be used when you have a bunch of different things to do, based on the situation/context.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
* Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author)&lt;br /&gt;
* Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;br /&gt;
* Effective Java 2nd Edition By Joshua Bloch&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54049</id>
		<title>Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=54049"/>
		<updated>2011-10-21T19:34:12Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page has been moved to [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_kp]&lt;br /&gt;
&lt;br /&gt;
==Design Patterns at a Glance==&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Design Patterns&lt;br /&gt;
! Singleton&lt;br /&gt;
! Adapter&lt;br /&gt;
! Command&lt;br /&gt;
! Strategy&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Purpose&lt;br /&gt;
| To ensure a class has only one instance, and also to provide a global point of access to it&lt;br /&gt;
| To convert the interface of a class into another interface the clients expects&lt;br /&gt;
| To encapsulate method invocations so as to decouple caller from the implementation details&lt;br /&gt;
| To perform a bunch of different things to do, based on the situation/context&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Advantages&lt;br /&gt;
| Sane usage of global namespace by avoiding unnecessary global variables and providing on-demand (lazy) instantiations.&lt;br /&gt;
| It lets classes work together that could not otherwise because of incompatible interfaces.&lt;br /&gt;
| It allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
| It lets the algorithms vary independently from clients that use those.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! Disadvantages&lt;br /&gt;
| Introduces global state into system and complicates unit testing.&lt;br /&gt;
| Adapter has to implement the entire target interface. Selective functionality implementation is not an option.&lt;br /&gt;
| Having Command objects specific to each action ends up cluttering the design, especially in the context of MVC architectures &amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx]&amp;lt;/ref&amp;gt;&lt;br /&gt;
| Increases the number of objects and all algorithms use the same interface. &amp;lt;ref&amp;gt; [www.cs.toronto.edu/~arnold/407/.../stateStrategy/state_strat_pres.ppt] &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
|}&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53973</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53973"/>
		<updated>2011-10-21T04:58:37Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''''1. SINGLETON PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
# You might want to have only one Window Manager to manage all your open windows in your system.&lt;br /&gt;
# Logging, where it provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. &amp;lt;ref&amp;gt;[http://www.oodesign.com/singleton-pattern.html Logger Classes]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''2. ADAPTER PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
==='''''3. COMMAND PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''4. STRATEGY PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;In computer programming, the strategy pattern is a design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&amp;quot; - Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Strategy_pattern Stratey Pattern Wikipedia]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example code for Strategy pattern====&lt;br /&gt;
Here we will see how strategy pattern can be used to sort a given list of real numbers using either BubbleSort() or QuickSort().&lt;br /&gt;
&lt;br /&gt;
Below is an interface to describe the individual algorithms.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public interface SortingInterface {&lt;br /&gt;
      public void sort(double[] list);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now implement both the Quicksort &amp;amp; Bubblesort strategies.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class QuickSort implements SortingInterface {&lt;br /&gt;
      //QuickSort will implement the sort() with the quicksort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
             //Do quick sort here&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
public class BubbleSort implements SortingInterface {&lt;br /&gt;
      &lt;br /&gt;
      //BubbleSort will implement the sort() with the bubblesort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
            //Do bubble sort here  &lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now define a Strategy context that maintains a reference to a Strategy object(Bubblesort or Quicksort) and forwards client requests to that strategy.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Context {&lt;br /&gt;
private SortingInterface algorithm = null;&lt;br /&gt;
&lt;br /&gt;
public void sortGivenList(double[] list) {&lt;br /&gt;
       algorithm.sort(list);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Getter method for algorithm&lt;br /&gt;
public SortingInterface getAlgorithm() {&lt;br /&gt;
       return algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Setter method for algorithm&lt;br /&gt;
public void setAlgorithm(SortingInterface algorithm) {&lt;br /&gt;
       this.algorithm = algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the client picks one of the available strategies(Quicksort or Bubblesort) in the context and sorts the List according to that strategy as shown below.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
      &lt;br /&gt;
      //Here is the List&lt;br /&gt;
      double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};&lt;br /&gt;
&lt;br /&gt;
      //Now define the Context&lt;br /&gt;
      Context context = new Context();&lt;br /&gt;
&lt;br /&gt;
      //Now pick your strategy i.e. Quicksort or Bubblesort&lt;br /&gt;
      context.setAlgorithm(new BubbleSort());&lt;br /&gt;
&lt;br /&gt;
      ///Now, sort it using the strategy you picked&lt;br /&gt;
      context.sortGivenList(list);&lt;br /&gt;
      &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
*Sorting a list: where the strategy can be to choose the sorting algorithm itself (QuickSort, HeapSort, etc.) at runtime depending on the input data. &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Sorting a llist using Strategy pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Layout_manager Layout Managers] in UI toolkits: where you can decide at runtime what layout is to be chosen for the GUI to be displayed.&amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern Strategy Pattern Real world examples]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Differences between Command and Strategy Pattern====&lt;br /&gt;
*A Command Pattern encapsulates a single action/algorithm whereas the Strategy pattern provides us with a number of actions/algorithms which can be selected based on a number of factors.&lt;br /&gt;
*A Command Pattern object has a single method but with a generic signature whereas Strategy pattern may have as many different methods provided.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
*The objective of the Singleton pattern as defined in Design Patterns is to &amp;quot;ensure a class has only one instance, and  also to provide a global point of access to it&amp;quot;.&amp;lt;ref&amp;gt;[http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/b746fa87-5e52-4474-b5f7-688c7f14823c Why or Why not Singleton]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Adapter Pattern converts the interface of a class into another interface the clients expects. This decouples the client and adaptee and allows them to work together.&lt;br /&gt;
* Command Pattern encapsulates method invocations, by which pieces of computation are crystallized, hence the object invoking the computation doesn't need to worry about how things are done.&lt;br /&gt;
*Strategy pattern should be used when you have a bunch of different things to do, based on the situation/context.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
* Head First Design Patterns By Elisabeth Freeman (Author), Eric Freeman (Author), Bert Bates (Author), Kathy Sierra (Author)&lt;br /&gt;
* Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides&lt;br /&gt;
* Effective Java 2nd Edition By Joshua Bloch&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53970</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53970"/>
		<updated>2011-10-21T04:55:44Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''''1. SINGLETON PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
# You might want to have only one Window Manager to manage all your open windows in your system.&lt;br /&gt;
# Logging, where it provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed. &amp;lt;ref&amp;gt;[http://www.oodesign.com/singleton-pattern.html Logger Classes]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''2. ADAPTER PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
==='''''3. COMMAND PATTERN'''''===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''''4. STRATEGY PATTERN'''''===&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;In computer programming, the strategy pattern is a design pattern, whereby algorithms can be selected at runtime. Formally speaking, the strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.&amp;quot; - Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Strategy_pattern Stratey Pattern Wikipedia]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example code for Strategy pattern====&lt;br /&gt;
Here we will see how strategy pattern can be used to sort a given list of real numbers using either BubbleSort() or QuickSort().&lt;br /&gt;
&lt;br /&gt;
Below is an interface to describe the individual algorithms.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public interface SortingInterface {&lt;br /&gt;
      public void sort(double[] list);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now implement both the Quicksort &amp;amp; Bubblesort strategies.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class QuickSort implements SortingInterface {&lt;br /&gt;
      //QuickSort will implement the sort() with the quicksort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
             //Do quick sort here&lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
public class BubbleSort implements SortingInterface {&lt;br /&gt;
      &lt;br /&gt;
      //BubbleSort will implement the sort() with the bubblesort version.&lt;br /&gt;
      public void sort(double[] list) {&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
            //Do bubble sort here  &lt;br /&gt;
      }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now define a Strategy context that maintains a reference to a Strategy object(Bubblesort or Quicksort) and forwards client requests to that strategy.&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Context {&lt;br /&gt;
private SortingInterface algorithm = null;&lt;br /&gt;
&lt;br /&gt;
public void sortGivenList(double[] list) {&lt;br /&gt;
       algorithm.sort(list);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Getter method for algorithm&lt;br /&gt;
public SortingInterface getAlgorithm() {&lt;br /&gt;
       return algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//Setter method for algorithm&lt;br /&gt;
public void setAlgorithm(SortingInterface algorithm) {&lt;br /&gt;
       this.algorithm = algorithm;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Finally, the client picks one of the available strategies(Quicksort or Bubblesort) in the context and sorts the List according to that strategy as shown below.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Client {&lt;br /&gt;
&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
      &lt;br /&gt;
      //Here is the List&lt;br /&gt;
      double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};&lt;br /&gt;
&lt;br /&gt;
      //Now define the Context&lt;br /&gt;
      Context context = new Context();&lt;br /&gt;
&lt;br /&gt;
      //Now pick your strategy i.e. Quicksort or Bubblesort&lt;br /&gt;
      context.setAlgorithm(new BubbleSort());&lt;br /&gt;
&lt;br /&gt;
      ///Now, sort it using the strategy you picked&lt;br /&gt;
      context.sortGivenList(list);&lt;br /&gt;
      &lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Applications====&lt;br /&gt;
*Sorting a list: where the strategy can be to choose the sorting algorithm itself (QuickSort, HeapSort, etc.) at runtime depending on the input data. &amp;lt;ref&amp;gt;[http://java-x.blogspot.com/2006/12/implementing-strategy-pattern-in-java.html Sorting a llist using Strategy pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Layout_manager Layout Managers] in UI toolkits: where you can decide at runtime what layout is to be chosen for the GUI to be displayed.&amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern Strategy Pattern Real world examples]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Differences between Command and Strategy Pattern====&lt;br /&gt;
*A Command Pattern encapsulates a single action/algorithm whereas the Strategy pattern provides us with a number of actions/algorithms which can be selected based on a number of factors.&lt;br /&gt;
*A Command Pattern object has a single method but with a generic signature whereas Strategy pattern may have as many different methods provided.&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
*The objective of the Singleton pattern as defined in Design Patterns is to &amp;quot;ensure a class has only one instance, and  also to provide a global point of access to it&amp;quot;.&amp;lt;ref&amp;gt;[http://social.msdn.microsoft.com/forums/en-US/architecturegeneral/thread/b746fa87-5e52-4474-b5f7-688c7f14823c Why or Why not Singleton]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Adapter Pattern converts the interface of a class into another interface the clients expects. This decouples the client and adaptee and allows them to work together.&lt;br /&gt;
* Command Pattern encapsulates method invocations, by which pieces of computation are crystallized, hence the object invoking the computation doesn't need to worry about how things are done.&lt;br /&gt;
*Strategy pattern should be used when you have a bunch of different things to do, based on the situation/context.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53897</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53897"/>
		<updated>2011-10-21T03:24:08Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Conceptual Work-out of the Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
==='''SINGLETON'''===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows -&lt;br /&gt;
&lt;br /&gt;
[[Image:Adapter kp1.png]]&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Adapter_kp1.png&amp;diff=53894</id>
		<title>File:Adapter kp1.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Adapter_kp1.png&amp;diff=53894"/>
		<updated>2011-10-21T03:23:58Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53890</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53890"/>
		<updated>2011-10-21T03:22:44Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Overview */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it. Notice that the constructor is &amp;quot;private&amp;quot;. So external classes, cannot instantiate the object of class &amp;quot;Singleton&amp;quot; directly. The only way to get an instance of this class is by using the getInstance() method.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() { //Notice that the constructor is private.&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows -&lt;br /&gt;
[[Image:Adapter kp.png]]&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Adapter_kp.png&amp;diff=53888</id>
		<title>File:Adapter kp.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Adapter_kp.png&amp;diff=53888"/>
		<updated>2011-10-21T03:22:35Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53883</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53883"/>
		<updated>2011-10-21T03:20:12Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Adapter */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton] is a design pattern which imposes a restriction on the class to instantiate exactly one object of that class.&lt;br /&gt;
&lt;br /&gt;
====Implementation====&lt;br /&gt;
*In Java, We can create a [http://en.wikipedia.org/wiki/Thread-safe thread-safe] &amp;amp; [http://en.wikipedia.org/wiki/Lazy_initialization lazy version] of Singleton as follows. The comments in the code help you understand the Lazy &amp;amp; thread-safe aspect of it.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
public class Singleton {&lt;br /&gt;
        private static Singleton instance;&lt;br /&gt;
 &lt;br /&gt;
        private Singleton() {&lt;br /&gt;
                //Do nothing. Initialize the object only when the first time getInstance() is called.&lt;br /&gt;
        }&lt;br /&gt;
 &lt;br /&gt;
        public static synchronized Singleton getInstance() { &lt;br /&gt;
&lt;br /&gt;
        //The keyword &amp;quot;synchronized&amp;quot; makes it thread safe so that two threads invoking getInstance()  &lt;br /&gt;
        //at the same time cannot create two instances when a context switch happens so as to &lt;br /&gt;
        //facilitate this scenario. In general this can happen even with 'n' threads invoking getInstance().&lt;br /&gt;
        //&amp;quot;synchronized&amp;quot; keyword is used to eliminate such scenarios.&lt;br /&gt;
&lt;br /&gt;
                if (null == instance) {&lt;br /&gt;
                        instance = new Singleton();&lt;br /&gt;
                }&lt;br /&gt;
                return instance;&lt;br /&gt;
        }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*In Ruby, we can achieve singleton classes by mixing-in the 'Singleton' module as follows. Here, &amp;quot;SingletonClass&amp;quot; is the name of the singleton class that is being created.&lt;br /&gt;
 &amp;lt;nowiki&amp;gt;&lt;br /&gt;
require 'singleton'&lt;br /&gt;
class SingletonClass&lt;br /&gt;
    include Singleton&lt;br /&gt;
    ...&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/nowiki&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====When should we use Singleton ?  ==== &lt;br /&gt;
There is a lot of criticism to the use of singleton pattern. So, how do we decide whether an object should be singleton or not ?&lt;br /&gt;
For an object to be considered as a singleton object, they must satisfy three requirements:&lt;br /&gt;
#controls concurrent access to a shared resource.&lt;br /&gt;
#access to the resource will be requested from multiple, disparate parts of the system.&lt;br /&gt;
#there can be only one object. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/228164/on-design-patterns-when-to-use-the-singleton When should we use Singleton ?]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Advantages====&lt;br /&gt;
*Singletons are often preferred to global variables as they don't pollute the global [http://en.wikipedia.org/wiki/Namespace namespace] with unnecessary variables &amp;amp; also can be instantiated only when needed unlike global variables which always consume resources.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks====&lt;br /&gt;
*Introduces a global state into the application.&lt;br /&gt;
*Can make unit testing classes in isolation difficult.&lt;br /&gt;
Checkout the [http://www.youtube.com/watch?v=-FRm3VPhseI this] video from Misko Hevery which explains in detail when the usage of singletons is not exercised.&amp;lt;ref&amp;gt;[http://www.youtube.com/watch?v=-FRm3VPhseI Why Singletons are bad]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
 “If it walks like a duck and quacks like a duck, then it might be a turkey wrapped with a Duck Adapter.”&lt;br /&gt;
&lt;br /&gt;
=====Definition=====&lt;br /&gt;
The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. &lt;br /&gt;
- Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
=====Overview=====&lt;br /&gt;
* Adapter pattern involves wrapping objects to make their interfaces look like something they are not. This enables us to adapt a design expecting one interface to a class that implements a different interface. &lt;br /&gt;
* Real World Adapters - The name “Adapter Design Pattern” is derived from the fact that the design pattern exactly mirror the behavior of a real world adapter, but in an Object Oriented Manner. Consider a normal use-case of an Adapter in real world. If you own a laptop manufactured in the US and want to connect it to a wall-socket plug in Europe, you will not be able to do so. The wall socket plug in Europe exposes an AC outlet and the US laptop charger is not designed to work with that directly. So the Adapter sits between the plug of your laptop and the European wall-socket outlet. Its job is to adapt the European outlet so that you can plug your laptop to it and receive power.&lt;br /&gt;
* On the similar lines, consider that you have an existing software system and you want to make it work against some new third-party vendor class library. Now this new vendor might have designed their library such that the interface exposed by it is different that the previous vendor library against which you have the working software system. Changing your existing code to match this new vendor interface might prove to be a cumbersome and high-cost operation. Also if you decide to change the library sometime again the future, you would have to do the same changes again. Enter Adapter Design Pattern. &lt;br /&gt;
* The Adapter Design Pattern acts as the middleman by receiving requests from the client and converting them into requests that make sense to the vendor classes.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be depicted as follows - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Example usage of Adapter Pattern=====&lt;br /&gt;
* Third Party Libraries: Wrappers are used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.&lt;br /&gt;
* Wrapper Functions in Java: in java there is wrapper functions for primatives.  For example the Integer class is a wrapper class for the primitive int&lt;br /&gt;
* An example would be where a square class can be wrapped so that it can be used as a rectangle also.&lt;br /&gt;
* Transformation of format of Dates: &amp;quot;Transforming the format of dates. YYYY-MM-DD to MM/DD/YYYY or DD/MM/YYYY&amp;quot;&lt;br /&gt;
&lt;br /&gt;
=====Conceptual Work-out of the Adapter Pattern=====&lt;br /&gt;
* Suppose the object that is going to be making the requests is called as “Client”. The Client is implemented expecting some interface.&lt;br /&gt;
* Let “Adaptee” be an object that can perform the actions that the Client is going to request. However, the interface implemented by the “Adaptee”, that is the methods or even method signatures exposed by the Adaptee differ than what the Client expects.&lt;br /&gt;
* Now, to make Client and Adaptee work together, we use the Adapter Design Pattern. This Adapter will need to implement the interface expected by the Client. Let us call this interface as the “target interface.” So the methods exposed by the Adapter interface conform to what the Client expects. The Adapter will also hold an instance of the “Adaptee.” This will ensure that Adapter can call the methods of this instance of Adaptee. Thus, the classic implementation of Adapter Pattern is using the Object-Oriented concept of “Composition”&lt;br /&gt;
&lt;br /&gt;
Pictorially, it can be viewed as follows - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Java=====&lt;br /&gt;
* We will use the standard Duck-Turkey example. Suppose, there is an interface “Duck” which exposes methods “quack” and “fly”. Let us assume that there is an interface “Turkey”, exposing “gobble” and “fly”. Let us also assume that the “fly” supported by Turkey is not the same as the “fly” supported by the Duck. (Turkey can not fly as high as a duck can or something on those lines.) &lt;br /&gt;
&lt;br /&gt;
 public interface Duck {&lt;br /&gt;
        public void quack();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
 public interface Turkey {&lt;br /&gt;
        public void gobble();&lt;br /&gt;
        public void fly();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Suppose, there is a ‘MallardDuck’ class that implements Duck Interface. &lt;br /&gt;
&lt;br /&gt;
 public class MallardDuck implements Duck {&lt;br /&gt;
    public void quack() {&lt;br /&gt;
        System.out.println(“Quack\n”);&lt;br /&gt;
    }&lt;br /&gt;
    public void fly() {&lt;br /&gt;
       System.out.println(“Fly\n”);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Now, suppose enough number of Objects of “MallardDuck” are not present and therefore we want some Turkeys to be adapted to support Duck Interface. This means that a Client will fire method invocations expecting a Duck Interface. Hence, ‘Duck’ is our target interface. As explained in the previous section, the Adapter would need to implement the target interface. This should internally call Turkey’s methods. An instance of Turkey will be passed to this Adapter.&lt;br /&gt;
&lt;br /&gt;
 public class TurkeyAdapter implements Duck {&lt;br /&gt;
     Turkey turkey;&lt;br /&gt;
     public TurkeyAdapter(Turkey turkey) {&lt;br /&gt;
          this.turkey = turkey;&lt;br /&gt;
     }&lt;br /&gt;
     /* quack method calls the gobble method of the Turkey*/&lt;br /&gt;
     public void quack() {&lt;br /&gt;
         turkey.gobble();&lt;br /&gt;
     }&lt;br /&gt;
     public void fly() {&lt;br /&gt;
        turkey.fly();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
* Testing that Adapter works: Suppose, there is a function testDuck which calls the “quack” and “fly” methods of the “Duck” passed to it. Following code creates a WildTurkey object. Passes that object to an instance of TurkeyAdapter class specified above. The corresponding TurkeyAdapter class is then passed to the testDuck method. &lt;br /&gt;
&lt;br /&gt;
 static void testDuck(Duck duck) {&lt;br /&gt;
    duck.quack();&lt;br /&gt;
    duck.fly();&lt;br /&gt;
 }&lt;br /&gt;
 WildTurkey turkey = new WildTurkey();&lt;br /&gt;
 Duck turkeyAdapter = new TurkeyAdapter(turkey);&lt;br /&gt;
 testDuck(turkeyAdapter);&lt;br /&gt;
&lt;br /&gt;
* In this way, adapter pattern allows us to use a client with an incompatible interface by creating an adapter that does the conversion. This results in decoupling the client from the implemented interface. &lt;br /&gt;
* However, if we expect the interface to change over time, the adapter encapsulates that changes so that the client doesn’t have to be modified each time it needs to operate against a different interface. &lt;br /&gt;
* This is possible because the Adapter pattern binds the client to an interface and not an implementation. We could use several adapters each converting a different backend set of classes as long as they adhere to the same target interface.&lt;br /&gt;
&lt;br /&gt;
=====Coding Example - Adapter Pattern in Ruby=====&lt;br /&gt;
&lt;br /&gt;
* Let us elaborate on the same example that was used in the lecture. Suppose we have classes SquarePeg, RoundPeg and RoundHole. RoundHole class supports a method peg_fits? which expects a “peg” object as an input. The method determines if the peg fits in it or not if the radius of the peg passed as an argument is smaller than the radius of the RoundHole. Now since SquarePeg does not have a radius, we will need an Adapter that converts the “width” attribute of SqurePeg into radius and then checks if that SquarePeg can fit into the RoundHole or not.&lt;br /&gt;
&lt;br /&gt;
 class SquarePeg&lt;br /&gt;
   attr_reader :width&lt;br /&gt;
   def initialize(width)&lt;br /&gt;
  	@width = width&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundPeg&lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(radius)&lt;br /&gt;
  	@radius = radius&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 class RoundHole &lt;br /&gt;
   attr_reader :radius&lt;br /&gt;
   def initialize(r)&lt;br /&gt;
      @radius = r&lt;br /&gt;
   end&lt;br /&gt;
   def peg_fits?(peg)&lt;br /&gt;
      peg.radius &amp;lt;= radius&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here is the Adapter class:&lt;br /&gt;
&lt;br /&gt;
 class SquarePegAdapter&lt;br /&gt;
   def initialize(square_peg)&lt;br /&gt;
      @peg = square_peg&lt;br /&gt;
   end	&lt;br /&gt;
   def radius&lt;br /&gt;
      Math.sqrt(((@peg.width/2) ** 2)*2)&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
 hole = RoundHole.new(4.0)&lt;br /&gt;
 4.upto(7) do |i|&lt;br /&gt;
	peg = SquarePegAdapter.new(SquarePeg.new(i.to_f))&lt;br /&gt;
	if hole.peg_fits?( peg )&lt;br /&gt;
    	puts &amp;quot;peg #{peg} fits in hole #{hole}&amp;quot;&lt;br /&gt;
	else&lt;br /&gt;
    	puts &amp;quot;peg #{peg} does not fit in hole #{hole}&amp;quot;&lt;br /&gt;
	end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
=====Object Adapters vs. Class Adapters=====&lt;br /&gt;
&lt;br /&gt;
* All the examples of Adapter that we have seen so far are the Object Adapters. &lt;br /&gt;
* Implementing Class Adapter is tricky since it requires multiple inheritance support in the programming language.&lt;br /&gt;
* In case of Object Adapters, we use “Composition” i.e. the Adapter holds an instance of Adaptee. In the case of Class Adapters, we use “Inheritance” i.e. the Adapter class is inherited from both Target class and the Adaptee class. &lt;br /&gt;
* The Class Adapter is thus committed to a specific adaptee class. But the hidden advantage behind this is that it does not require to re-implement the entire Adaptee class. There is also the fact that a Class Adapter can just override the methods of Adaptee is it wants to. &lt;br /&gt;
* Therefore, Class Adapters are not as flexible as Object Adapters.&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53759</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53759"/>
		<updated>2011-10-21T01:56:32Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Pattern equals Encapsulating Method Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53748</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53748"/>
		<updated>2011-10-21T01:50:07Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Conceptual work-out of the Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53746</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53746"/>
		<updated>2011-10-21T01:49:45Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Conceptual work-out of the Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
[[Image:Command kp.png]]&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Command_kp.png&amp;diff=53742</id>
		<title>File:Command kp.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Command_kp.png&amp;diff=53742"/>
		<updated>2011-10-21T01:48:53Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53730</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53730"/>
		<updated>2011-10-21T01:44:38Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html Design Patterns in Java]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command Command Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern Command Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx Design Patterns-codeproject]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby Design Patterns in Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr Wiki Chapter On Closures]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/ Ruby Design Patterns]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm Undo By a Command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53719</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53719"/>
		<updated>2011-10-21T01:39:35Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. &amp;lt;ref&amp;gt;[http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://java.dzone.com/articles/design-patterns-command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Command_pattern ]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. &amp;lt;ref&amp;gt;[http://www.alexmcferron.com/command.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. &amp;lt;ref&amp;gt;[http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
&amp;lt;ref&amp;gt;[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. &amp;lt;ref&amp;gt;[http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. &amp;lt;ref&amp;gt;[http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://sourcemaking.com/design_patterns/command]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
&amp;lt;ref&amp;gt;[http://www.voelter.de/data/pub/metacommand.pdf]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53705</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53705"/>
		<updated>2011-10-21T01:35:58Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Advanced Command Pattern Features */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
=====Supporting Undo operation=====&lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;NoCommand&amp;quot; Object=====&lt;br /&gt;
The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
=====The &amp;quot;Meta&amp;quot; Command Pattern=====&lt;br /&gt;
Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53700</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53700"/>
		<updated>2011-10-21T01:35:14Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Coding example: Command Pattern in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53697</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53697"/>
		<updated>2011-10-21T01:33:49Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Conceptual work-out of the Command Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
* At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53694</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53694"/>
		<updated>2011-10-21T01:32:54Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Coding example: Command Pattern in Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53690</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53690"/>
		<updated>2011-10-21T01:31:55Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Coding example: Command Pattern in Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
    GarageDoor garagedoor;&lt;br /&gt;
    public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
       this.garagedoor = garagedoor;&lt;br /&gt;
    }&lt;br /&gt;
    /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
    public void execute() {&lt;br /&gt;
       garagedoor.up();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
     Command cmd;&lt;br /&gt;
     public void setCommand(Command cmd) {&lt;br /&gt;
        this.cmd = cmd;&lt;br /&gt;
     }&lt;br /&gt;
     public void buttonPressed() {&lt;br /&gt;
        cmd.execute();&lt;br /&gt;
     }&lt;br /&gt;
     /* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
        Command object was set to. &lt;br /&gt;
     */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
         GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
         GarageDoorOpenCommand gdOpenCmd = new GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
         rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
         rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53672</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53672"/>
		<updated>2011-10-21T01:25:52Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Case Study==&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53669</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53669"/>
		<updated>2011-10-21T01:25:33Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;h6&amp;gt;&amp;lt;i&amp;gt;&amp;lt;b&amp;gt;Command Design Pattern: Encapsulating Invocations&amp;lt;/b&amp;gt;&amp;lt;/i&amp;gt;&amp;lt;/h6&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53665</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53665"/>
		<updated>2011-10-21T01:25:00Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
There are various types of Design Patterns, viz [http://en.wikipedia.org/wiki/Creational_pattern creational patterns], [http://en.wikipedia.org/wiki/Structural_pattern structural patterns], and [http://en.wikipedia.org/wiki/Behavioral_pattern behavioral patterns], each of which consists numerous examples inturn. But that is not the scope of our discussion. So, let us limit ourselves to the following 4 pattern examples.&lt;br /&gt;
#Singleton pattern (type of Creational pattern).&lt;br /&gt;
#Adapter pattern (type Structural pattern).&lt;br /&gt;
#Command pattern (type of Behavioral pattern).&lt;br /&gt;
#Strategy pattern (type of Behavioral pattern).&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;h4&amp;gt;&amp;lt;i&amp;gt;&amp;lt;b&amp;gt;Command Design Pattern: Encapsulating Invocations&amp;lt;/b&amp;gt;&amp;lt;/i&amp;gt;&amp;lt;/h4&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53661</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53661"/>
		<updated>2011-10-21T01:24:30Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;h4&amp;gt;Command Design Pattern: Encapsulating Invocations&amp;lt;/h4&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53659</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53659"/>
		<updated>2011-10-21T01:24:01Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;h3&amp;gt;Command Design Pattern: Encapsulating Invocations&amp;lt;h3&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53657</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53657"/>
		<updated>2011-10-21T01:23:36Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Command */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
 &amp;quot;Command Design Pattern: Encapsulating Invocations&amp;quot;&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53654</id>
		<title>CSC/ECE 517 Fall 2011/ch4 4h kp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch4_4h_kp&amp;diff=53654"/>
		<updated>2011-10-21T01:22:53Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
This wiki article discusses about some of the commonly used &amp;amp; easy to understand Desgin patterns[http://en.wikipedia.org/wiki/Design_pattern_(computer_science)] in the software industry. Specifically, we will be studying about the Singleton, Adapter, Command &amp;amp; Strategy patterns.&lt;br /&gt;
&lt;br /&gt;
==Design Pattern==&lt;br /&gt;
===Definition===&lt;br /&gt;
Some of the common definitions available online are as follows.&lt;br /&gt;
*&amp;quot;In [http://en.wikipedia.org/wiki/Software_engineering software engineering], a design [http://en.wikipedia.org/wiki/Pattern pattern] is a general reusable solution to a commonly occurring problem within a given context in [http://en.wikipedia.org/wiki/Software_design software design]. A design pattern is not a finished design that can be transformed directly into [http://en.wikipedia.org/wiki/Code_(computer_programming) code]. It is a description or template for how to solve a problem that can be used in many different situations. [http://en.wikipedia.org/wiki/Object-oriented Object-oriented] design patterns typically show relationships and [http://en.wikipedia.org/wiki/Interaction interaction]s between [http://en.wikipedia.org/wiki/Class_(computer_science) class]es or [http://en.wikipedia.org/wiki/Object_(computer_science) object]s, without specifying the final application classes or objects that are involved.&amp;quot; -Wikipedia &amp;lt;ref&amp;gt;[http://en.wikipedia.org/wiki/Design_pattern_(computer_science) Design Pattern in Computer Science, Wikipedia]&amp;lt;/ref&amp;gt; &lt;br /&gt;
&lt;br /&gt;
*&amp;quot;A design pattern is a repeatable solution to a software engineering problem. Unlike most program-specific solutions, design patterns are used in many programs. Design patterns are not considered finished product; rather, they are templates that can be applied to multiple situations and can be improved over time, making a very robust software engineering tool. Because development speed is increased when using a proven prototype, developers using design pattern templates can improve coding efficiency and final product readability.&amp;quot; -Techopedia &amp;lt;ref&amp;gt;[http://www.techopedia.com/definition/18822/design-pattern Techopedia explains Design Pattern]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In a layman's term, Design Patterns are &lt;br /&gt;
*descriptions of what experienced designers know.&lt;br /&gt;
*hints for choosing classes &amp;amp; methods&lt;br /&gt;
*higher order abstractions for program organization&lt;br /&gt;
*used to weigh design tradeoffs&lt;br /&gt;
*used to avoid limitations of implementation language. &amp;lt;ref&amp;gt;[http://norvig.com/design-patterns/ppframe.htm Design Patterns in Dynamic Languages - Peter Norvig]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Examples===&lt;br /&gt;
&lt;br /&gt;
===Singleton===&lt;br /&gt;
&lt;br /&gt;
===Adapter===&lt;br /&gt;
&lt;br /&gt;
===Command===&lt;br /&gt;
&lt;br /&gt;
====Command Design Pattern: Encapsulating Invocations====&lt;br /&gt;
&lt;br /&gt;
====Definition====&lt;br /&gt;
&amp;quot;By encapsulating method invocation, we can crystallize pieces of computation, so that&lt;br /&gt;
the object invoking the computation doesn't need to worry about how things are done. It just uses the crystallized method to get things done&amp;quot; - Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
====Overview====&lt;br /&gt;
The command pattern allows one to decouple the requester of an action from the object that actually performs the action.&lt;br /&gt;
&lt;br /&gt;
This decoupling is achieved by introducing a command object which encapsulates the request to do something on an object i.e.the action to be taken or the methods to be invoked and exposes these via a single API. So the requester will only need to invoke this well exposed and simple API of the command object and the implementation of this API will contain calls to the methods of the object on which actual actions are to be done. [http://www.javaworld.com/javaworld/javatips/jw-javatip68.html]&lt;br /&gt;
It achieves two things - One, the requester object code can remain simple. It does not need to take into consideration the details about how the action is going to be performed, it will only need to worry about the API exposed by the Command Object corresponding to the object whose actions are to be invoked. And two, the object on which the actions are invoked need not worry about who invoked them. The only &amp;quot;route&amp;quot; via which they would have been invoked is via the Command object specific to this object.&lt;br /&gt;
[http://java.dzone.com/articles/design-patterns-command]&lt;br /&gt;
&lt;br /&gt;
====Example Usage of Command Pattern====&lt;br /&gt;
* A calculator with unlimited number of undo’s and redo’s&lt;br /&gt;
* &amp;quot;Thread pools” - A typical, general-purpose thread pool class might have a public addTask() method that adds a work item to an internal queue of tasks waiting to be done. It maintains a pool of threads that execute commands from the queue. [http://en.wikipedia.org/wiki/Command_pattern ]&lt;br /&gt;
* Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.&lt;br /&gt;
[http://www.codeproject.com/KB/books/DesignPatterns.aspx]&lt;br /&gt;
&lt;br /&gt;
====Conceptual work-out of the Command Pattern====&lt;br /&gt;
* Let us assume that there is an object &amp;quot;Client&amp;quot; which needs to invoke some action of Object &amp;quot;Receiver&amp;quot;.&lt;br /&gt;
* Let us also assume that this &amp;quot;action&amp;quot; is a cumulative computation and it might involve invoking multiple methods of Receiver object.&lt;br /&gt;
In absence of Command Pattern, &amp;quot;Client&amp;quot; will invoke &amp;quot;Receiver's&amp;quot; methods via code statements like receiver.method1(), receeiver.method2() etc. This would mean that Client has to know exactly which methods and in which sequence are required to be called for the specified action &lt;br /&gt;
to take place. Thus, it implies a higher level of coupling and hence a dependency between Client and Receiver objects.&lt;br /&gt;
However, using a Command object specific to the Receiver object will help in decoupling this dependency.&lt;br /&gt;
* The Command object will only provide a single method, say &amp;quot;execute()&amp;quot; and this method will encapsulate all the method invocations of Receiver object. In this way, the methods of Receiver object for executing an action and the Receiver object itself are bound together in the Command object. [http://www.alexmcferron.com/command.html]&lt;br /&gt;
* The Client object will then create the Command Object and pass it to an intermediate &amp;quot;Invoker&amp;quot; object where it will get stored.&lt;br /&gt;
At some point in the future, the Invoker object will invoke the &amp;quot;execute()&amp;quot; method of the Command Object passed to it, which in turn will culminate in calling all the methods of Receiver Object that are required to be called for the original specified action to take place.&lt;br /&gt;
&lt;br /&gt;
Pictorially, this can be visualized as follows - &lt;br /&gt;
&lt;br /&gt;
[http://www.allapplabs.com/java_design_patterns/command_pattern.html]&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Java====&lt;br /&gt;
&lt;br /&gt;
This example is inspired from the example given in Head First Design Patterns&lt;br /&gt;
&lt;br /&gt;
Suppose there is a &amp;quot;RemoteControl&amp;quot; that operates lights and other such devices in a house. The remote might have on and off buttons for every light and pressing those buttons might only invoke &amp;quot;on&amp;quot; and &amp;quot;off&amp;quot; actions on those lights. However what if the same Remote is to be&lt;br /&gt;
used for controlling a GarageDoor? GarageDoor will not have on and off methods but &amp;quot;up&amp;quot; and &amp;quot;down&amp;quot; methods. One way around this would be including &amp;quot;if&amp;quot; statements in RemoteControl code that checks if the device being controlled is a GarageDoor, then invoke &amp;quot;up&amp;quot; instead of &amp;quot;on&amp;quot;. However, this is not a robust method. If you decide to support a new device in the future, more &amp;quot;else if&amp;quot; statements will get added. The RemoteControl logic will become complex and it will be closely coupled with all the devices. This does not exhibit good Object Oriented design. However, using Command Pattern will ease out the problem. We can have one Command Object per device and specifically for each action on each device.&lt;br /&gt;
&lt;br /&gt;
This command object's execute() method will encapsulate calls to &amp;quot;on&amp;quot; or &amp;quot;off&amp;quot;. This achieves two things. One, the RemoteControl code can now be simple. It will only invoke &amp;quot;execute()&amp;quot; method of whichever device is being controlled. Also adding support of new devices in the future becomes easy.&lt;br /&gt;
&lt;br /&gt;
Java provides an Interface called &amp;quot;Command&amp;quot;. It supports only one method, &amp;quot;execute()&amp;quot; &lt;br /&gt;
The Command Interface can be follows &lt;br /&gt;
&lt;br /&gt;
 public interface Command {&lt;br /&gt;
    public void execute();&lt;br /&gt;
 };&lt;br /&gt;
&lt;br /&gt;
Now, there will be a GarageDoorOpen command object that should implement the Command Interface. &lt;br /&gt;
&lt;br /&gt;
 public class GarageDoorOpenCommand implements Command {&lt;br /&gt;
           GarageDoor garagedoor;&lt;br /&gt;
	 &lt;br /&gt;
	 public GarageDoorOpenCommand(GarageDoor garagedoor) {&lt;br /&gt;
	      this.garagedoor = garagedoor;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
	 /* execute method encapsultes the call to &amp;quot;up&amp;quot; */&lt;br /&gt;
	 public void execute() {&lt;br /&gt;
	      garagedoor.up();&lt;br /&gt;
	 }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Now remains the client and Invoker classes. Our Invoker class should only call execute method on whatever Command Object is passed to it.&lt;br /&gt;
Also, the Client object should create a Command object, pass it to Invoker object. &lt;br /&gt;
&lt;br /&gt;
 public class RemoteControlInvoker {&lt;br /&gt;
           Command cmd;&lt;br /&gt;
	&lt;br /&gt;
	public void setCommand(Command cmd) {&lt;br /&gt;
	    this.cmd = cmd;&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void buttonPressed() {&lt;br /&gt;
	    cmd.execute();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	/* The Invoker object will only call execute on the command object to which its local   &lt;br /&gt;
                Command object was set to. &lt;br /&gt;
            */&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class RemoteControl {&lt;br /&gt;
      public static void main(String[] args) {&lt;br /&gt;
		RemoteControlInvoker rmtInvoker = new RemoteControlInvoker();&lt;br /&gt;
		&lt;br /&gt;
	            GarageDoor garageDoor = new GarageDoor();&lt;br /&gt;
		GarageDoorOpenCommand gdOpenCmd = new      GarageDoorOpenCommand(garageDoor);&lt;br /&gt;
		&lt;br /&gt;
		rmtInvoker.setCommand(gdOpenCmd);   //Pass the created Command Object to Invoker&lt;br /&gt;
		rmtInvoker.buttonPressed();         //Let the Invoker invoke action on the Receiver GarageDoor&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In this way, the Command object encapsulates a request by binding together a set of actions on a specific receiver. It does this&lt;br /&gt;
by packaging the actions and the receiver and exposing just one method - execute(). From the outside, no other objects really know &lt;br /&gt;
what actions get performed on a receiver, they just know that by calling &amp;quot;execute()&amp;quot;, their request will be processed.&lt;br /&gt;
&lt;br /&gt;
====Coding example: Command Pattern in Ruby====&lt;br /&gt;
&lt;br /&gt;
In Ruby, because of the presence of &amp;quot;Closures&amp;quot;, implementing a Command Pattern is a fairly straightforward. [http://www.scribd.com/doc/2217773/Design-Patterns-in-Ruby]&lt;br /&gt;
&lt;br /&gt;
Formally, a closure is basically a function or a method (or even a block, in the context of Ruby) that has the following twp properties:&lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods.blocks&lt;br /&gt;
* It saves the lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch1_1d_sr]&lt;br /&gt;
&lt;br /&gt;
The “Proc” class in Ruby supports a method “call” by which the block of code saved in the Proc class can be “called” and executed. In this scenario, the Proc class (which might be an output of the ‘lambda’ function) can be considered as an equivalent of the “invoker” class and the block of code passed to it to be the “Command” object.&lt;br /&gt;
&lt;br /&gt;
However, using Procs for implementing Command Pattern is not applicable always. Whenever it is required to pass commands between address spaces or save commands to a file and later load them into a Ruby program. Proc objects can not be stored or restored using marshal module. Therefore, for following two reasons, using Proc objects is not enough for Command Pattern - &lt;br /&gt;
* When command objects need to be Persistent&lt;br /&gt;
* When command objects need to be sent to a remote objects.&lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
In such cases, one would have to explicitly implement Command objects via “Command” class. &lt;br /&gt;
&lt;br /&gt;
Below is an example of Command Pattern in Ruby using an explicit class and not using the Proc class. In this example, “CheckMemory” extends Command class and the Installer class supports “install”, “uninstall” methods. Installer class need not worry about the instance of class passed to the “add_command” method. &lt;br /&gt;
[http://blog.ashwinraghav.com/2011/03/14/design-patterns-in-ruby-composite-iterator-commandpart-2/]&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
    def initialize(description, proc1, proc2)&lt;br /&gt;
       @description = description&lt;br /&gt;
       @function =  proc1&lt;br /&gt;
       @inverse = proc2&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def execute&lt;br /&gt;
       @function.call unless @function.nil?&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def unexecute&lt;br /&gt;
       @inverse.call unless @inverse.nil?&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class CheckMemory &amp;lt; Command ##ireversible&lt;br /&gt;
    def initialize&lt;br /&gt;
       proc1 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Checking Memory...&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       proc2 = Proc.new do&lt;br /&gt;
         puts &amp;quot;Mem Check need not be reversed&amp;quot;&lt;br /&gt;
       end&lt;br /&gt;
       super(&amp;quot;Checking memory avalability&amp;quot;, proc1, proc2)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 class Installer&lt;br /&gt;
    def initialize&lt;br /&gt;
       @commands = []&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def add_command command&lt;br /&gt;
       @commands &amp;lt;&amp;lt; command&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def install&lt;br /&gt;
       @commands.each {|c| c.execute}&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def uninstall&lt;br /&gt;
       @commands.reverse.each do |command|&lt;br /&gt;
          command.unexecute&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 installer = Installer.new&lt;br /&gt;
 installer.add_command(CheckMemory.new)&lt;br /&gt;
 installer.add_command(CreateFile.new)&lt;br /&gt;
 installer.installinstaller.uninstall&lt;br /&gt;
&lt;br /&gt;
====Advanced Command Pattern Features====&lt;br /&gt;
&lt;br /&gt;
* Supporting Undo operation: &lt;br /&gt;
Providing &amp;quot;undo&amp;quot; functionality to a software is an important feature addition. Many softwares like editors need to keep track of previous actions performed and then let user undo some or all of them on demand. The Command Pattern lends itself in a very nice manner for &lt;br /&gt;
implementing such functionality. [http://stackoverflow.com/questions/2214874/implementing-the-command-pattern]&lt;br /&gt;
&lt;br /&gt;
When Commands support undo, they have an undo() method that mirros the execute() method. Whatever execute() last did, undo() reverses it.&lt;br /&gt;
In the above code example, the Command Interface would need to have a method undo and the GarageDoorOpenCommand class will need to implement&lt;br /&gt;
it. It can just have a call to &amp;quot;down&amp;quot; method on the GarageDoor.&lt;br /&gt;
In more general sense, we would need to have a Command object that always points to the last Command that was executed. Whenever an undo&lt;br /&gt;
action needs to be done, the undo() method of object to which this command object is pointing to would be called. [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;NoCommand&amp;quot; Object: The NoCommand object is an example of null object. A null object is useful when there is no meaningful object&lt;br /&gt;
to return and the responsibility of handling null objects is not adviced.&lt;br /&gt;
[http://sourcemaking.com/design_patterns/command]&lt;br /&gt;
&lt;br /&gt;
* The &amp;quot;Meta&amp;quot; Command Pattern: Meta Command Pattern allows us to create macros of Command objects so that multiple actions can be executed&lt;br /&gt;
via a single call. This means that the execute() method of a MetaCommand Object will involve a series of calls of &amp;quot;execute()&amp;quot; methods&lt;br /&gt;
of other Command Objects.&lt;br /&gt;
[http://www.voelter.de/data/pub/metacommand.pdf]&lt;br /&gt;
&lt;br /&gt;
===Strategy===&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=50589</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=50589"/>
		<updated>2011-09-25T17:27:11Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://diveintopython.org/getting_to_know_python/declaring_functions.html]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature. [http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html]&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References and External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 1. Closures: A Simple Explanation (using ruby) ''by Alan Skorkin'']&lt;br /&gt;
&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html 2. Raganwald; Closures and Higher Order Functions]&lt;br /&gt;
&lt;br /&gt;
[http://diveintopython.org/getting_to_know_python/declaring_functions.html 3. Dive into Python: 2.2. Declaring Functions]&lt;br /&gt;
&lt;br /&gt;
[http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf 4. Functional Programming and the Lambda Calculus ''by Stephen A. Edwards'']&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 5. Closures in Ruby ''by Paul Cantrell'']&lt;br /&gt;
&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ 6. Understanding Ruby Blocks, Procs and Lambdas ''by Robert Sosinski'']&lt;br /&gt;
&lt;br /&gt;
[http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/ 7. Tiny Hippos; Closure in JavaScript - With Examples]&lt;br /&gt;
&lt;br /&gt;
[http://stackoverflow.com/questions/233673/lexical-closures-in-python 8. Stack Overflow; Lexical closures in Python]&lt;br /&gt;
&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html 9. Neal Gafter's Blog; A definition of Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 10. Blocks and Closures in Ruby: A Conversation with Yukihiro Matsumoto, Part III ''by Bill Venners'']&lt;br /&gt;
&lt;br /&gt;
[http://porkrind.org/missives/closures-in-straight-c/ 11. Porkrind Dot Org Missives; Closures in Straight C]&lt;br /&gt;
&lt;br /&gt;
[http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/ 12. Closure Sale; Lambda Abstractions in C]&lt;br /&gt;
&lt;br /&gt;
[http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html 13. &amp;quot;Blocks&amp;quot; in Clang (aka closures) ''by Chris Lattner'']&lt;br /&gt;
&lt;br /&gt;
[http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html 14. Insight Into Nothing: How to Hack Closures in your C Code (or &amp;quot;The Closure Design-Pattern in C&amp;quot;)]&lt;br /&gt;
&lt;br /&gt;
[http://kfsone.wordpress.com/2010/02/21/c-closures/ 15. kfsone's pittance; C++ Closures]&lt;br /&gt;
&lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses 16. Stack Overflow; C++ Functors - and their uses]&lt;br /&gt;
&lt;br /&gt;
[http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm 17. Java in a Nutshell; 3.12. Anonymous Classes]&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
[http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html 18. Ricky's Technical Blog; Why Java Needs Closures (It Already Has Them)]&lt;br /&gt;
&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html 19. Neal Gafter's Blog; A Definition of Closures]&lt;br /&gt;
&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures 20. James Gosling: on the Java Road; Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html 21. JavaWorld; Understanding the closures debate ''By Klaus Kreft and Angelika Langer'']&lt;br /&gt;
&lt;br /&gt;
[http://c2.com/cgi/wiki?ScopeAndClosures 22. Cunningham &amp;amp; Cunningham, Inc.; Scope and Closures]&lt;br /&gt;
&lt;br /&gt;
[http://lua-users.org/lists/lua-l/2004-11/msg00185.html 23. Closure of lexical environment in Scheme closures ''by Dr. Rich Artym'']&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 24. Zdeněk Troníček's blog; Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 25. Lambda expressions and closures for C++ ''by Jeremiah Willcock, Jaakko J¨arvi, Doug Gregor, Bjarne Stroustrup, and Andrew Lumsdaine'']&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 26. Thought Palace; Blocks/Closures For C!]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46875</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46875"/>
		<updated>2011-09-07T16:40:48Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* References and External Links */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature. [http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html]&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References and External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 1. Closures: A Simple Explanation]&lt;br /&gt;
&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html 2. Closures and Higher order functions]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 3. Closures a form of Anonymous]&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 4. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 6. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 7. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
[http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf 8. Functional Calculus using Lambda notation]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9. Closures in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ 10. Understanding Ruby Blocks and Closures]&lt;br /&gt;
&lt;br /&gt;
[http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/ 11. Closures and JavaScript]&lt;br /&gt;
&lt;br /&gt;
[http://stackoverflow.com/questions/233673/lexical-closures-in-python 12. Lexical Closures in Python]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46874</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46874"/>
		<updated>2011-09-07T16:40:32Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature. [http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html]&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References and External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 1. Closures: A Simple Explanation]&lt;br /&gt;
&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html 2. Closures and Higher order functions]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 3. Closures a form of Anonymous]&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 4. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 6. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 7. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
[http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf 8. Functional Calculus using Lambda notation]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9. Closures in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ 10. Understanding Ruby Blocks and Closures]&lt;br /&gt;
&lt;br /&gt;
[http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/ 11. Closures and JavaScript]&lt;br /&gt;
&lt;br /&gt;
[http://stackoverflow.com/questions/233673/lexical-closures-in-python Lexical Closures in Python]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46873</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46873"/>
		<updated>2011-09-07T16:39:42Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature. [http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html]&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References and External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 1. Closures: A Simple Explanation]&lt;br /&gt;
&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html 2. Closures and Higher order functions]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 3. Closures a form of Anonymous]&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 4. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 5. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 6. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 7. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
[http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf 8. Functional Calculus using Lambda notation]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9. Closures in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ 10. Understanding Ruby Blocks and Closures]&lt;br /&gt;
&lt;br /&gt;
[http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/ 11. Closures and JavaScript]&lt;br /&gt;
&lt;br /&gt;
[http://stackoverflow.com/questions/233673/lexical-closures-in-python Lexical Closures in Python]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46872</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46872"/>
		<updated>2011-09-07T16:30:32Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* C : function pointers */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature. [http://lists.cs.uiuc.edu/pipermail/cfe-dev/2008-August/002670.html]&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46871</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46871"/>
		<updated>2011-09-07T16:28:48Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Closures and Static Scoping */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
  (let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46870</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46870"/>
		<updated>2011-09-07T16:28:28Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Closures and Static Scoping */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
Consider the below Scheme code snippet. The example is derived from [http://lua-users.org/lists/lua-l/2004-11/msg00185.html this thread].&lt;br /&gt;
&lt;br /&gt;
(let* ((foo                     ; define foo&lt;br /&gt;
            10)&lt;br /&gt;
       (incfoo1                 ; define incfoo1&lt;br /&gt;
            (lambda () (+ foo 0.1)))&lt;br /&gt;
       (bar                     ; define bar&lt;br /&gt;
            65))                ; bar not used (just for symmetry)&lt;br /&gt;
     (incfoo1))                 ; prints 10.1&lt;br /&gt;
&lt;br /&gt;
The variable &amp;quot;foo&amp;quot; is in static scope when the function &amp;quot;incfoo1&amp;quot; is defined. Later, when incfoo1 is called, it will print &amp;quot;10.1&amp;quot;, thus remembering the value &amp;quot;10&amp;quot; that foo was assigned to, even though it is no longer in scope at the time of the call.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46868</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46868"/>
		<updated>2011-09-07T16:15:26Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example implementation using Function Objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from &lt;br /&gt;
[http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46867</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46867"/>
		<updated>2011-09-07T16:15:07Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example implementation using Function Objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from [ http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread]. about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme, both of which are statically typed.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46865</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46865"/>
		<updated>2011-09-07T16:14:12Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* C++ : Function Objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. This example is cited from [ http://stackoverflow.com/questions/356950/c-functors-and-their-uses this discussion thread] about closures in C++&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping, is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such languages include JavaScript and Scheme.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46857</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46857"/>
		<updated>2011-09-07T16:07:26Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* C : function pointers */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. [http://porkrind.org/missives/closures-in-straight-c/]&lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. [http://mikeburrell.wordpress.com/2008/03/31/lambda-abstractions-in-c/]&lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
Static scoping, also known as lexical scoping is scoping in which variables are looked up according to the context in which they are defined.  This ensures that the lexical context is maintained in languages that allow for first class-functions, which means the first class functions create closures. [http://c2.com/cgi/wiki?ScopeAndClosures]  Examples of such classes include Javascript and Scheme.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46853</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46853"/>
		<updated>2011-09-07T15:58:50Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* An example implementation of Closures in C */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well. [http://nothingintoinsight.blogspot.com/2009/02/how-to-hack-closures-in-your-c-code-or.html]&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46851</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46851"/>
		<updated>2011-09-07T15:57:04Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Challenges For Closures in Statically Typed Languages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection. [http://www.artima.com/intv/closures.html]&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46850</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46850"/>
		<updated>2011-09-07T15:56:18Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example in Python */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined. [http://stackoverflow.com/questions/233673/lexical-closures-in-python]&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46849</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46849"/>
		<updated>2011-09-07T15:55:33Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example in JS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot; [http://tinyhippos.com/2010/07/05/closure-in-javascript-with-examples/]&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined.&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46317</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46317"/>
		<updated>2011-09-06T21:51:42Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example in Python */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
Closures are a topic of interest in computer science.  While they provide useful functionality, they are more often included in dynamic languages than in statically typed languages.  This article covers what closures are and why they are useful.  It also explains why implementing closures in statically typed languages is a challenge, giving examples along the way from both dynamically typed and statically typed languages.&lt;br /&gt;
&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
For a highly powerful and dynamically typed language like Python, closures act as one more useful feature.&lt;br /&gt;
Below is a simple example of closures in Python. The closure names &amp;quot;_inc&amp;quot; will remember the value of variable &amp;quot;step&amp;quot; which was in scope &lt;br /&gt;
when it the closure function was defined.&lt;br /&gt;
&lt;br /&gt;
 def counter(start=0, step=1): &lt;br /&gt;
      x = [start] &lt;br /&gt;
      def _inc(): &lt;br /&gt;
           x[0] += step &lt;br /&gt;
           return x[0]&lt;br /&gt;
      return _inc &lt;br /&gt;
 c = counter() &lt;br /&gt;
 c() # This will output &amp;quot;1&amp;quot;&lt;br /&gt;
 c() # This will output &amp;quot;2&amp;quot; &lt;br /&gt;
 c() # This will output &amp;quot;3&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
The following sections discuss specific statically typed languages in relation to closures.&lt;br /&gt;
&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes.&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes are unnamed classes that are simultaneously defined and instantiated with a single ''new'' operator.&lt;br /&gt;
The following define the syntax for anonymous inner classes: [http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm]&lt;br /&gt;
    new class-name ( [ argument-list ] ) { class-body } &lt;br /&gt;
&lt;br /&gt;
    new interface-name () { class-body } &lt;br /&gt;
&lt;br /&gt;
The following is an example closure implementation in Java from [http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html Ricky's Technical Blog].  The &amp;quot;closure&amp;quot; is in that the method run' inside the new 'Runnable' object can reference the variable 'use'.&lt;br /&gt;
   public void example()&lt;br /&gt;
   {&lt;br /&gt;
           final double use=Math.random()*10000;&lt;br /&gt;
   &lt;br /&gt;
           SwingUtilities.invokeLater(new Runnable()&lt;br /&gt;
           {&lt;br /&gt;
                   public void run()&lt;br /&gt;
                   {&lt;br /&gt;
                           System.out.println(use);&lt;br /&gt;
                   }&lt;br /&gt;
           });&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Anonymous inner classes have limitations as closures. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise and overly verbose in comparison to the use of closures in dynamically typed languages like Ruby.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46244</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46244"/>
		<updated>2011-09-06T18:49:52Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example implementation using Function Objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Limitations of Statically Typed Languages===&lt;br /&gt;
====Lexical Scope====&lt;br /&gt;
====Functions not as first class citizens of the language====&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. [http://stackoverflow.com/questions/356950/c-functors-and-their-uses]&lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes, though there are limitations. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise as it is to use closures in dynamically typed languages like Ruby. [http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46243</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46243"/>
		<updated>2011-09-06T18:48:17Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* C++ : function objects */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Limitations of Statically Typed Languages===&lt;br /&gt;
====Lexical Scope====&lt;br /&gt;
====Functions not as first class citizens of the language====&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : Function Objects====&lt;br /&gt;
&lt;br /&gt;
Implementing closures in C++ requires a different philosophy because of the Object Oriented nature of the language. Just having a struct of function pointer pointing to the function to be used as closure and a pointer to the context of the function will not suffice. In C++, it is not possible to pass around pointer to a member function. In C++ world, a member function is part of the context of the object and hence can not be accessed when the object ceases to exist or goes out of scope. On the inside, calling a member function is equivalent to calling a piece of code i.e. the function with a hidden argument &amp;quot;Object *this&amp;quot; which is actually a reference to the object instance [http://kfsone.wordpress.com/2010/02/21/c-closures/]. A specific C++ program construct called as a &amp;quot;functor&amp;quot; of function object can be used to implement an equivalent of closures.&lt;br /&gt;
&lt;br /&gt;
===== Example implementation using Function Objects =====&lt;br /&gt;
&lt;br /&gt;
Function objects are objects specifically designed to be used with a syntax similar to that of functions. In C++, this is achieved by defining member function operator()(). In other words, a functor or a function object would be the object of a class that defines the function call operator i.e. &amp;quot;operator () ()&amp;quot; as a member function. This will mean that using the object with &amp;quot;()&amp;quot; would be equivalent to calling a function. Also the data members of this class can be thought of as the variables that constitute the context of the function. &lt;br /&gt;
&lt;br /&gt;
Consider the below example. Whenever you create the object &amp;quot;Adder10&amp;quot; and actually do the call of &amp;quot;Adder10&amp;quot; with argument &amp;quot;20&amp;quot;, it will add 20 to 10 and return the result. The private data member &amp;quot;x&amp;quot; is set once via the constructor at object initialization. Whatever is passed as the argument will be added to the value of &amp;quot;x&amp;quot; and be returned.&lt;br /&gt;
&lt;br /&gt;
 class ClosureAdd {&lt;br /&gt;
  ClosureAdd(int x) : x(x) {}&lt;br /&gt;
  int operator()(int y) { return x + y; }&lt;br /&gt;
&lt;br /&gt;
  private:&lt;br /&gt;
     int x;&lt;br /&gt;
 };&lt;br /&gt;
 // Now you can use it like this:&lt;br /&gt;
 ClosureAdd Adder10(10);                 // create a functor&lt;br /&gt;
 int i = Adder10(20);                    // and &amp;quot;call&amp;quot; it&lt;br /&gt;
 cout &amp;lt;&amp;lt; i                               // this will print &amp;quot;30&amp;quot; as the answer&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes, though there are limitations. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise as it is to use closures in dynamically typed languages like Ruby. [http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46195</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46195"/>
		<updated>2011-09-06T14:30:51Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* An example implementation of Closures in C */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Limitations of Statically Typed Languages===&lt;br /&gt;
====Lexical Scope====&lt;br /&gt;
====Functions not as first class citizens of the language====&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
Below is the definition of the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : function objects====&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes, though there are limitations. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise as it is to use closures in dynamically typed languages like Ruby. [http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46181</id>
		<title>CSC/ECE 517 Fall 2011/ch1 1d sr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2011/ch1_1d_sr&amp;diff=46181"/>
		<updated>2011-09-06T05:25:22Z</updated>

		<summary type="html">&lt;p&gt;Sskanitk: /* Example in JS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Wiki Chapter: CSC/ECE 517 Fall 2011/ch1 1d sr&lt;br /&gt;
&lt;br /&gt;
''Closures in statically typed languages.  Most languages that implement closures are dynamically typed.  It is a challenge to implement closures in a statically typed language.  Explain why, and cover attempts to mix the two.  Consider also closures and static scoping, as in Scheme.''&lt;br /&gt;
__TOC__&lt;br /&gt;
==Introduction==&lt;br /&gt;
==Closures==&lt;br /&gt;
&lt;br /&gt;
===What are Closures?===&lt;br /&gt;
A '''closure''' is basically a function or a method (or a block, in the context of ruby) that has the following two properties: &lt;br /&gt;
* It is a first-class function, meaning it can be passed around like an object or as a value parameter to other functions/methods/blocks&lt;br /&gt;
* It saves its lexical environment, meaning it captures the variables within scope at its creation and maintains them even if they later go out of scope.[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
&lt;br /&gt;
In order for a programming language to be able to support closures, it must support the notion of &amp;quot;first class functions.&amp;quot; &lt;br /&gt;
A first class function is a function that can be treated like an object, such as passing it as a parameter or returning the function as the result of another method. [http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html] Since a closure can be passed around as a value before calling it, it can be called in a completely different scope than the one in which it was created and it is because of this that it needs to retain the knowledge of the lexical environment in which it was defined. [http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html]&lt;br /&gt;
&lt;br /&gt;
===Why Closures ===&lt;br /&gt;
&lt;br /&gt;
* For [http://en.wikipedia.org/wiki/Functional_languages functional languages], which themselves are essentially stateless, closures offer a way to store some kind of state at least for as long as the closure lives. [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Closures help functional languages to be terse in expressing logic. Closures also offer a very succinct way of performing some neat programmatic operations i.e. if a closure modifies the value of a variable, it will retain the new value the next time the closure was invoked.  [http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
* Higher order, special purpose functions like select and inject in Ruby, which do a lot of useful stuff with very little code are possible only because the language supports closures.&lt;br /&gt;
* Currying of functions in languages like Ruby is only made possible through the use of closures. Currying is taking a function and one or more of its parameters to produce a new function with fewer parameters, which can be useful for human readability and coding.[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
* For procedural or imperative languages, the argument for closures is a twofold one. Procedural languages already have mechanism to store state via the use of global variables, static variables etc. but closures offer a way to pass around units of computation that can be executed later. The function pointers and the callback function ideology in C is centered around this motivation. For object-oriented imperative languages like C++ or the Objective-C, closures provide for the lack of a syntactically light-weight way to define simple object functions for the effective use of several generic algorithms like those offered by Standard Template Library.&lt;br /&gt;
&lt;br /&gt;
===Closures in Dynamically Typed Languages===&lt;br /&gt;
&lt;br /&gt;
A dynamically typed language is a programming language which does majority of its type-checking at run-time instead of compile-time [http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing]. '''In dynamic typing, values have types but variables do not.''' Hence, a variable can refer to a value of any type. This important property of dynamically typed languages offers itself as a convenient way of implementing and supporting closures. For closures, a variable can point to a block of code and the associated lexical environment. A special-purpose programming construct called &amp;quot;'''''lambda'''''&amp;quot; is used in some languages to express '''anonymous functions''' i.e functions which are not bound to a name at runtime. &lt;br /&gt;
Lambda is used to generate new functions dynamically. The concept of &amp;quot;lambda&amp;quot; has been derived from the lambda calculus in the functional programming [http://www.cs.columbia.edu/~sedwards/classes/2010/w4115-spring/functional.pdf]. &lt;br /&gt;
&lt;br /&gt;
====Example use of Closures in Dynamically Typed Langauges====&lt;br /&gt;
The following are examples of closure usage in some of the dynamically typed languages. These examples cover a particular and common usage of closures, but all the aspects and subtleties of closures in a particular language (in Ruby, for example, there are Seven distinct ways of implementing closure or closure-like structures[http://innig.net/software/ruby/closures-in-ruby.rb]) will not be covered here.&lt;br /&gt;
&lt;br /&gt;
=====Example in Ruby=====&lt;br /&gt;
&lt;br /&gt;
In Ruby, for all intents and purposes, &amp;quot;Blocks&amp;quot; [http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/] are closures. They are closed with respect to the variables defined in the context in which they were created, regardless of the context in which they are called. The subtle difference is that a &amp;quot;Block&amp;quot; can not be passed as a specific named parameter and &amp;quot;yield&amp;quot; is the only way by which control can be given to the block that was passed to the method in which yield is called. &lt;br /&gt;
&lt;br /&gt;
 class ClosureTest&lt;br /&gt;
  &lt;br /&gt;
    def initialize(x)&lt;br /&gt;
       @x = x&lt;br /&gt;
    end&lt;br /&gt;
  &lt;br /&gt;
    def call_closure(ClosureBlock)&lt;br /&gt;
      ClosureBlock.call @x&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 a = 100&lt;br /&gt;
 ClosureBlock = lambda {|x| puts x+a}&lt;br /&gt;
 ClosureObj = ClosureTest.new(10)&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;110&amp;quot;&lt;br /&gt;
 a = 200&lt;br /&gt;
 ClosureObj.call_closure(ClosureBlock)      # This will output &amp;quot;210&amp;quot;&lt;br /&gt;
&lt;br /&gt;
As seen in the above example, &amp;quot;ClosureBlock&amp;quot; is a closure. The use of lambda construct means that the ClosureBlock variable would be of type &amp;quot;Proc&amp;quot;. When ClosureBlock is defined, the variable &amp;quot;a&amp;quot; is in its scope and hence it will remember the value that &amp;quot;a&amp;quot; was bound to. However when ClosureObj, an object of class ClosureTest calls &amp;quot;call_closure&amp;quot; method with ClosureObj passed as a parameter (closures can be passed around as objects), it will remember the value of &amp;quot;a&amp;quot; even though &amp;quot;a&amp;quot; is now no longer in scope and will print &amp;quot;100+10&amp;quot; as the answer. On the similar notes, when &amp;quot;a&amp;quot; is modified and call_closure is invoked again, the ClosureBlock will pick up the value of &amp;quot;a&amp;quot; in the lexical context in which ClosureBlock was created i.e. it will pick up the latest value of &amp;quot;a&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
=====Example in JS=====&lt;br /&gt;
&lt;br /&gt;
JavaScript is also a dynamically typed language and it supports closures in its most rudimentary form.&lt;br /&gt;
It is not required to use lambda construct to be able to use closures in JavaScript.&lt;br /&gt;
&lt;br /&gt;
In below example, in function &amp;quot;clickMe&amp;quot;, the output of 'alert' would be &amp;quot;originalValue&amp;quot;.&lt;br /&gt;
The function block gets created on the fly while calling &amp;quot;calledFunction&amp;quot; in &amp;quot;clickMe&amp;quot;. The passed function is a closure and it remembers the value of &amp;quot;value&amp;quot; that was within the context of its definition. So when &amp;quot;passedFunction&amp;quot; is called from calledFunction, it will assign the &amp;quot;newValue&amp;quot; to &amp;quot;value&amp;quot; even though &amp;quot;value&amp;quot; is not in the scope of calledFunction. This is possible because of closures. The output of next 'alert; would be this &amp;quot;newValue&amp;quot;&lt;br /&gt;
&lt;br /&gt;
   function calledFunction(passedFunction) {&lt;br /&gt;
          passedFunction(&amp;quot;newValue&amp;quot;);&lt;br /&gt;
   }&lt;br /&gt;
   function clickMe() {&lt;br /&gt;
        var value = &amp;quot;originalValue&amp;quot;;&lt;br /&gt;
        alert(value);&lt;br /&gt;
        calledFunction(function(externalValue) {&lt;br /&gt;
            value = externalValue;&lt;br /&gt;
        });&lt;br /&gt;
        alert(value);&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
=====Example in Python=====&lt;br /&gt;
&lt;br /&gt;
==Closures in Statically Typed Languages==&lt;br /&gt;
===Challenges For Closures in Statically Typed Languages===&lt;br /&gt;
Closures are not usually implemented in statically typed languages, due to their nature.  The following are some obstacles statically typed languages must overcome:&lt;br /&gt;
* While dynamically typed languages allow for any variable to be associated with any type, static languages require types declared at compile time.  This would require a specific type for closures if they were implemented in a statically typed language.[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
* Many statically typed languages keep track of in-scope variables with a stack-based system: variables are pushed on when entering a scope and popped when exiting a scope.  This can be a challenge for implementing closures in statically typed languages, since closures must maintain access to variables even when they go out of scope.&lt;br /&gt;
* Since closures require saving the lexical environment of its definition, the ways and means provided by a language for doing this determines the level of difficulty and effectively the feasibility of implementing closures in that language. In statically typed languages like C, one way of doing this would be to make a copy of all the variables that are needed when a closure was defined and passing this copy around as its context. Alternative to this copying strategy, one way could be to retain a reference to them, thus making them not eligible for garbage collection.&lt;br /&gt;
&lt;br /&gt;
===Limitations of Statically Typed Languages===&lt;br /&gt;
====Lexical Scope====&lt;br /&gt;
====Functions not as first class citizens of the language====&lt;br /&gt;
===Implementing Closures in Statically Typed Languages===&lt;br /&gt;
====C : function pointers====&lt;br /&gt;
&lt;br /&gt;
* The concept of closures requires that a block of code along with the lexical context of its creation needs to be saved. C's context is based on the local variables which are created on the stack frame corresponding to the function currently being executed, the registers of the CPU which might store specific values and the global variables. Anything other than this is handled by the dynamic memory allocation provided by malloc. &lt;br /&gt;
&lt;br /&gt;
* The programming construct of &amp;quot;'''''function pointers'''''&amp;quot; is a useful tool for implementing closures in C. A function pointer is, as the name suggests, a pointer which stores address of any function. One can pass this function pointer holding the address of a particular function to another function as a parameter. The function which receives the function pointer as a parameter can now &amp;quot;call&amp;quot; or execute the function pointed to by the function pointer. This, in its most rudimentary form, is the basic technique by which C can pass along blocks of code to another functions. &lt;br /&gt;
&lt;br /&gt;
* However the definition of closure also mandates that the lexical context at the time of its creation need also be saved and accessible later. This proves to be a painful task and one needs a logic to provide this functionality in the most concise and acceptable manner. One way to do this would be to provide a programmer defined struct which holds the values of all the variables which were &amp;quot;in scope&amp;quot; of the function that is to be treated as closure. &lt;br /&gt;
&lt;br /&gt;
* Note here that the struct variable which stores the values of all the variables in the lexical context of the function under consideration must not be &amp;quot;statically&amp;quot; allocated i.e. it must not be allocated on the stack of the method currently being executed. So this context saving structure variable needs to be allocated from the heap using malloc and the pointer to this &amp;quot;context structure&amp;quot; will need to be passed along with the function pointer to any functions that need to execute this later. However, note that because of the inherent nature of &amp;quot;statically&amp;quot; typed behavior, one would have to associate a particular function pointer with the function with matching signature and hence this combination of function pointer and user data struct pointer is not exactly type independent. &lt;br /&gt;
&lt;br /&gt;
* &amp;quot;Type independence&amp;quot; in this context means that a function block would have to be closely tied with its signature like the data types of the parameters that the function expects, the data type of the return value that the function should return etc. So to create a different closure corresponding to a function of different signature, one would need the definition of another function pointer with compatible signature.&lt;br /&gt;
&lt;br /&gt;
=====An example implementation of Closures in C=====&lt;br /&gt;
&lt;br /&gt;
Consider the below Ruby block. The function &amp;quot;caller&amp;quot; defines a closure using lambda construct and returns it to a variable called ClosureVar. The variable &amp;quot;x&amp;quot; which is passed as a parameter to function &amp;quot;caller&amp;quot; forms the part of lexical environment that the closure should save and keep track of. &lt;br /&gt;
&lt;br /&gt;
  def caller x&lt;br /&gt;
       puts x&lt;br /&gt;
       lambda do&lt;br /&gt;
           x += 1&lt;br /&gt;
           puts &amp;quot;Inside closure&amp;quot;&lt;br /&gt;
           puts x&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   ClosureVar = caller(5)&lt;br /&gt;
   ClosureVar.call             # This will output 6&lt;br /&gt;
   ClosureVar.call             # This will output 7&lt;br /&gt;
&lt;br /&gt;
The below structure would be the placeholder for the closure implementation in C. Since for this example, &amp;quot;x&amp;quot; is the only variable which is part of the lexical context in which closure was defined, only that variable is included in the struct. If more variables are part of it, they would need to be included in the struct definition as well.&lt;br /&gt;
&lt;br /&gt;
  struct closure {&lt;br /&gt;
        void (* call_closure)(struct closure *);&lt;br /&gt;
        int x;&lt;br /&gt;
  };&lt;br /&gt;
&lt;br /&gt;
We will need to define the actual function which will hold the statements that were part of the block of code that constitutes the closure in the above ruby snippet.&lt;br /&gt;
&lt;br /&gt;
  void closure_block(struct closure * env) {&lt;br /&gt;
        env-&amp;gt;x += 1;&lt;br /&gt;
        printf (&amp;quot;block: x is %d\n&amp;quot;, env-&amp;gt;x);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
And finally, the C code snippet below would be the implementation of &amp;quot;caller&amp;quot; function.&lt;br /&gt;
&lt;br /&gt;
    void (*fptr_closure_block) (struct closure *) = 0;       /* Define a function pointer which can point to functions whose&lt;br /&gt;
                                                                signature matches that of closure_block.&lt;br /&gt;
                                                              */&lt;br /&gt;
    fptr_closure_block = closure_block;                      /* Make this function pointer point to closure_block */&lt;br /&gt;
 &lt;br /&gt;
    struct closure * caller(int x)&lt;br /&gt;
    {&lt;br /&gt;
         struct closure * ClosureVar = (struct closure *)malloc(sizeof(struct closure *));&lt;br /&gt;
         ClosureVar-&amp;gt;x = x;&lt;br /&gt;
         printf (&amp;quot;x is %d\n&amp;quot;,ClosureVar-&amp;gt;x);&lt;br /&gt;
         ClosureVar-&amp;gt;call_closure = fptr_closure_block;&lt;br /&gt;
         return ClosureVar;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
As can be seen from the above example, implementing a simple closure scenario in C involves a lot of messy logic and function pointer manipulation. For implementing more advanced feature like multiple closures, an even more complicated code would be required.  It is thus, not at all, intuitive to implement closures in C.&lt;br /&gt;
&lt;br /&gt;
====C++ : function objects====&lt;br /&gt;
&lt;br /&gt;
====Java : anonymous inner classes====&lt;br /&gt;
Java can provide similar functionality to closures through anonymous inner classes, though there are limitations. For simulating closures, the local variables from enclosing scopes used in the anonymous class must be declared ''final''.  This is because variables are not resolved in the enclosing scope, but in the class's scope.  Using Java's anonymous inner classes in this way is also not as simple to implement code-wise as it is to use closures in dynamically typed languages like Ruby. [http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
&lt;br /&gt;
James Gosling, regarded as the inventor of Java, stated that &amp;quot;closures were left out of Java initially more because of time pressures than anything else.&amp;quot;  He also explains inner classes being added to Java to alleviate the lack of closures, but that this was not a real solution.  Gosling feels he should have gone all the way to implementing closures back then. [http://blogs.oracle.com/jag/entry/closures] Proposals are currently being made for Java to include closures as a feature. [http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
&lt;br /&gt;
==Closures and Static Scoping==&lt;br /&gt;
===(Explanation)===&lt;br /&gt;
===Case study of Scheme===&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1. Matz discussion on Closures]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2. Closures in C++]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3. Closures in C]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4. Closures in Java]&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
&lt;br /&gt;
[http://www.artima.com/intv/closures.html 1]&lt;br /&gt;
&lt;br /&gt;
[http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1968.pdf 2]&lt;br /&gt;
&lt;br /&gt;
[http://jens.mooseyard.com/2008/08/blocksclosures-for-c/ 3]&lt;br /&gt;
&lt;br /&gt;
[http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html 4]&lt;br /&gt;
&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/ 5]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/First-class_function 6]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Functional_languages 7]&lt;br /&gt;
&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/ 8]&lt;br /&gt;
&lt;br /&gt;
[http://innig.net/software/ruby/closures-in-ruby.rb 9]&lt;br /&gt;
&lt;br /&gt;
==RESOURCES TO LOOK THROUGH IN WORKING ON THE WIKI - KURT==&lt;br /&gt;
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html]&lt;br /&gt;
[http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://www.artima.com/intv/closures.html]&lt;br /&gt;
[http://reprog.wordpress.com/2010/02/27/closures-finally-explained/]&lt;br /&gt;
[http://thejavacodemonkey.blogspot.com/2008/01/what-are-closures-and-what-do-they-mean.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/use-cases-for-closures.html]&lt;br /&gt;
[http://samdanielson.com/2007/9/6/an-introduction-to-closures-in-ruby]&lt;br /&gt;
[http://www.javaworld.com/javaworld/jw-06-2008/jw-06-closures.html]&lt;br /&gt;
[http://gafter.blogspot.com/2006/08/whats-point-of-closures.html]&lt;br /&gt;
[http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/]&lt;br /&gt;
[http://gafter.blogspot.com/2007/01/definition-of-closures.html]&lt;br /&gt;
[http://martinfowler.com/bliki/Closure.html]&lt;br /&gt;
[http://blogs.oracle.com/jag/entry/closures]&lt;/div&gt;</summary>
		<author><name>Sskanitk</name></author>
	</entry>
</feed>