<?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=Abhagav</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=Abhagav"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Abhagav"/>
	<updated>2026-09-29T03:09:43Z</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_2012/ch2b_2w36_av&amp;diff=70054</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=70054"/>
		<updated>2012-11-18T04:04:31Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Difference between factory method pattern and prototype pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implements the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which object they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The 'new' operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] for the prototype design pattern on the right:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:These example have been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(29,70)&amp;quot; or a &amp;quot;new Point(2967,59789)&amp;quot; and the cloned object would have similar state to those prototypes. Thus we can customize the state of the objects that will be created by this design pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=70047</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=70047"/>
		<updated>2012-11-18T03:24:02Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Java Sample code to show prototype design pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] for the prototype design pattern on the right:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:These example have been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69728</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69728"/>
		<updated>2012-11-17T00:51:16Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Prototype Design Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] for the prototype design pattern on the right:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:These example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69727</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69727"/>
		<updated>2012-11-17T00:50:48Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Java Sample code to show prototype design pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:These example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69726</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69726"/>
		<updated>2012-11-17T00:48:32Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69725</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69725"/>
		<updated>2012-11-17T00:47:12Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://www.dotnetlead.com/UML-Quick-Reference UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the [http://en.wikipedia.org/wiki/Composite_pattern Composite pattern], to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69723</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69723"/>
		<updated>2012-11-17T00:45:09Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://www.dotnetlead.com/UML-Quick-Reference UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or [http://en.wikipedia.org/wiki/Builder_pattern Builder patterns], which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69722</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69722"/>
		<updated>2012-11-17T00:43:41Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://www.dotnetlead.com/UML-Quick-Reference UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Abstract_factory_pattern The Abstract Factory], Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69718</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69718"/>
		<updated>2012-11-17T00:40:51Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the [http://www.dotnetlead.com/UML-Quick-Reference UML diagram] for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69711</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69711"/>
		<updated>2012-11-17T00:31:08Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the [http://www.dotnetlead.com/design-patterns/prototype prototype design pattern] comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69708</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69708"/>
		<updated>2012-11-17T00:26:59Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory &amp;lt;ref name=&amp;quot;msdn&amp;quot;&amp;gt;http://msdn.microsoft.com/en-us/library/orm-9780596527730-01-05.aspx&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69707</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69707"/>
		<updated>2012-11-17T00:24:29Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes &amp;lt;ref name=&amp;quot;differences&amp;quot;&amp;gt;http://community.topcoder.com/tc?module=Static&amp;amp;d1=tutorials&amp;amp;d2=prototypePattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69706</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69706"/>
		<updated>2012-11-17T00:21:19Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:This example has been taken from &amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69705</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69705"/>
		<updated>2012-11-17T00:16:48Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Prototype Design Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69704</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69704"/>
		<updated>2012-11-17T00:15:35Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern &amp;lt;ref name=&amp;quot;codeprototype&amp;quot;&amp;gt;http://www.codeproject.com/Articles/185348/Prototype-Design-Pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; ]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69703</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69703"/>
		<updated>2012-11-17T00:06:12Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype.&amp;lt;ref name=&amp;quot;javaprototype&amp;quot;&amp;gt;http://java.dzone.com/articles/intro-design-patterns-prototype&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69694</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69694"/>
		<updated>2012-11-16T23:52:33Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
* prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
* AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
* GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
*copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
*Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69693</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69693"/>
		<updated>2012-11-16T23:51:08Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of [http://en.wikipedia.org/wiki/Creational_pattern creational pattern].  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the [http://en.wikipedia.org/wiki/Unified_Modeling_Language UML diagram] on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
* Hide concrete classes from the client.&lt;br /&gt;
* Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
* Keep the number of classes in the system to a minimum.&lt;br /&gt;
* Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
* With the Composite pattern, to provide archiving.&lt;br /&gt;
* Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
* Flexibility is important.&lt;br /&gt;
* Objects can be extended in subclasses&lt;br /&gt;
* There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
* A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
* The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69690</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69690"/>
		<updated>2012-11-16T23:46:14Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
&lt;br /&gt;
•	Hide concrete classes from the client.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Keep the number of classes in the system to a minimum.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
•	With the Composite pattern, to provide archiving.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Factory Method pattern when'''&lt;br /&gt;
&lt;br /&gt;
•	Flexibility is important.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Objects can be extended in subclasses&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	There is a specific reason why one subclass would be chosen over another-this logic forms part of the Factory Method.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	A client delegates responsibilities to subclasses in parallel hierarchies.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern instead of:'''&lt;br /&gt;
&lt;br /&gt;
•	The Abstract Factory, Prototype, or Builder patterns, which are more flexible (though also more complex).The Prototype pattern to store a set of objects to clone from the abstract factory [15].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69689</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69689"/>
		<updated>2012-11-16T23:44:48Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
&lt;br /&gt;
•	Hide concrete classes from the client.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Keep the number of classes in the system to a minimum.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
•	With the Composite pattern, to provide archiving.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69688</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69688"/>
		<updated>2012-11-16T23:43:45Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Use the Prototype pattern when'''&lt;br /&gt;
&lt;br /&gt;
You want to:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Hide concrete classes from the client.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Add and remove new classes (via prototypes) at runtime.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Keep the number of classes in the system to a minimum.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Adapt to changing structures of data at runtime.&lt;br /&gt;
&lt;br /&gt;
'''Consider using this pattern:'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	With the Composite pattern, to provide archiving.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Instead of the Factory Method pattern, when subclasses start proliferating.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69687</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69687"/>
		<updated>2012-11-16T23:42:24Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
You will notice that in the factoryDoSomething method, the point that is created is initialized in the same way and cannot be customized1. The prototypeDoSomething method can create a point from any other point with any type of state assigned to it. We could have called it with a &amp;quot;new Point(23,85)&amp;quot; or a &amp;quot;new Point(2929,59483)&amp;quot; and the cloned object would have similar state to those prototypes. The, ahem, point of the matter is that we can customize the state of the objects that will be created by the prototype pattern. &lt;br /&gt;
&lt;br /&gt;
Another major difference between the two patterns is the type of classes that can be created. A factory pattern will know (either through a registry or through sub classing) the various class types that can be created. The prototype pattern is not restricted to this as long as the object can be cloned. This allows the cloning of objects that are loaded dynamically from a class loader or ddl library or some other source where the class of the object is unknown either to the application or the component itself. &lt;br /&gt;
&lt;br /&gt;
Lastly, a factory pattern can handle a limited set of class types efficiently but gets bogged down as the number of types increase. The more types a factory pattern can create, the more cumbersome the factory pattern becomes from the overhead of managing those classes (both in the factory itself and in creating the necessary supporting classes). If the classes that are managed by the factory pattern are a hierarchy of classes for any given implementation, that hierarchy is generally repeated for each type regardless of how similar each class is to any other implementation. If the factory pattern uses a registry of some sort, the registry becomes harder to manage and certainly consumes more resources. On the other hand, the prototype pattern does not suffer from these issues since the pattern is focused on an existing object. The pattern is very scalable as the types increase because it has no management or overhead associated to it. If a class hierarchy is involved for each implementation, the pattern becomes very efficient because it can reduce the number of redundant classes involved since any class can be simply cloned (in other words, you can mix and match classes from different types where applicable). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
To sum up, a prototype pattern provides benefits over a factory pattern when the state of the objects should can be customized by the calling application, the class types are dynamically loaded or otherwise unknown or when there is a large number of class type implementations that potentially deal with a lot of similar classes [14].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69686</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69686"/>
		<updated>2012-11-16T23:41:40Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public void factoryDoSomething(Factory factory) {&lt;br /&gt;
    Point pt = factory.createPoint();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public void prototypeDoSomething(Point prototype) {&lt;br /&gt;
    Point pt = (Point) prototype.clone();&lt;br /&gt;
    ... do something with the point ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69685</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69685"/>
		<updated>2012-11-16T23:40:38Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
===Difference between factory method pattern and prototype pattern===&lt;br /&gt;
&lt;br /&gt;
The prototype pattern and the factory pattern are very similar in both intent and functionality. Both are creational patterns that will create objects of some interface without needing to specifically know the underlying class types. &lt;br /&gt;
&lt;br /&gt;
The main difference between the two patterns however involves how objects are constructed. The factory pattern will, generally, construct an object using the same construction parameters each time. Each object will be initialized with the same state information and be roughly equivalent to each other. The prototype pattern, on the other hand, can use any clone able object that is given to it — even if those objects are of the same class type but with different state information assigned to them. Each object then becomes the prototype or template for any objects cloned from them. An example can demonstrate this:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69684</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69684"/>
		<updated>2012-11-16T23:39:37Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming] concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''AnimalClient.java'''&lt;br /&gt;
&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
 Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
 animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
 animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
 animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
 for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
 System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
 } // for [13]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69682</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69682"/>
		<updated>2012-11-16T23:37:59Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''Chicken.java'''&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
'''AnimalCreator.java'''&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
 if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
 return (Animal) chicken.clone();   &lt;br /&gt;
 } else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
 return (Animal) sheep.clone(); &lt;br /&gt;
 } // if &lt;br /&gt;
 return null;&lt;br /&gt;
 } // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
AnimalClient.java&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
Code:&lt;br /&gt;
01.AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
02.Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
03.animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
04.animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
05.animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
06.animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
07.animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
08.animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
09.animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
10.animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
11.for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
12.System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
13.} // for&lt;br /&gt;
&lt;br /&gt;
[13]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69681</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69681"/>
		<updated>2012-11-16T23:36:34Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
'''Animal.java'''&lt;br /&gt;
&lt;br /&gt;
The Animal class is the abstract prototype of the two concrete prototypes in the example. The client invokes methods on the two different concrete prototypes through the Animal type to ensure the client does not know the type of the concrete prototypes.&lt;br /&gt;
Most importantly, the Animal prototype defines a clone method to assist the two subtypes or concrete prototypes to clone themselves.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
 public Animal clone() {  &lt;br /&gt;
 Animal clonedAnimal = null;&lt;br /&gt;
 try {  &lt;br /&gt;
 clonedAnimal = (Animal) super.clone(); &lt;br /&gt;
 clonedAnimal.setDescription(description);  &lt;br /&gt;
 clonedAnimal.setNumberOfLegs(numberOfLegs);&lt;br /&gt;
 clonedAnimal.setName(name);&lt;br /&gt;
 } catch (CloneNotSupportedException e) {&lt;br /&gt;
 e.printStackTrace();   &lt;br /&gt;
 } // catch &lt;br /&gt;
 return clonedAnimal;   &lt;br /&gt;
 } // method clone&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Sheep.java'''&lt;br /&gt;
The Sheep object is a concrete prototype that extends the Animal prototype. The Sheep prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
&lt;br /&gt;
Code:&lt;br /&gt;
&lt;br /&gt;
 public class Sheep extends Animal {&lt;br /&gt;
&lt;br /&gt;
Chicken.java&lt;br /&gt;
The Chicken object is a concrete prototype that extends the Animal prototype. The Chicken prototype has a clone method to clone itself to create a new object.&lt;br /&gt;
Code:&lt;br /&gt;
public class Chicken extends Animal {&lt;br /&gt;
&lt;br /&gt;
AnimalCreator.java&lt;br /&gt;
The AnimalCreator class is used to create and manage prototype objects. The AnimalCreator class contains two concrete prototypes that are initialized during the initialization of the class. The AnimalCreator class forms part of the &amp;quot;Prototype&amp;quot; pattern by returning a cloned object (Animal) to the client without the client knowing the type of the prototype.&lt;br /&gt;
Code:&lt;br /&gt;
01.public Animal retrieveAnimal(String kindOfAnimal) {&lt;br /&gt;
02.if (&amp;quot;Chicken&amp;quot;.equals(kindOfAnimal)) {   &lt;br /&gt;
03.return (Animal) chicken.clone();   &lt;br /&gt;
04.} else if (&amp;quot;Sheep&amp;quot;.equals(kindOfAnimal)) { &lt;br /&gt;
05.return (Animal) sheep.clone(); &lt;br /&gt;
06.} // if&lt;br /&gt;
07. &lt;br /&gt;
08.return null;&lt;br /&gt;
09.} // method retrieveAnimal&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
AnimalClient.java&lt;br /&gt;
The AnimalClient class makes use of the AnimalCreator class to create a concrete prototypes of typeAnimal. The AnimalClient class does not know the type of the concrete prototypes but references them through the Animal prototype.&lt;br /&gt;
Code:&lt;br /&gt;
01.AnimalCreator animalCreator = new AnimalCreator();  &lt;br /&gt;
02.Animal[] animalFarm = new Animal[8];  &lt;br /&gt;
03.animalFarm[0] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);&lt;br /&gt;
04.animalFarm[1] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
05.animalFarm[2] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
06.animalFarm[3] = animalCreator.retrieveAnimal(&amp;quot;Chicken&amp;quot;);   &lt;br /&gt;
07.animalFarm[4] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
08.animalFarm[5] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
09.animalFarm[6] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
10.animalFarm[7] = animalCreator.retrieveAnimal(&amp;quot;Sheep&amp;quot;); &lt;br /&gt;
11.for (int i= 0; i&amp;lt;=7; i++) { &lt;br /&gt;
12.System.out.println(animalFarm[i].helloAnimal());   &lt;br /&gt;
13.} // for&lt;br /&gt;
&lt;br /&gt;
[13]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69680</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69680"/>
		<updated>2012-11-16T23:34:11Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Java Sample code to show prototype design pattern===&lt;br /&gt;
The following is an example of the Prototype Pattern. The prototype object is an Animal object. The Animal prototype contains two concrete prototype subclasses namely Sheep and Chicken. TheAnimalCreator class contains references to the two concrete prototypes. During the initialization of theAnimalCreator class the two concrete prototypes, Sheep and Chicken are created and stored as the two concrete prototypes members of the AnimalCreator class. The AnimalCreator class contains a retrieveAnimal method that clones a prototype Animal depending on the parameter that is passed to it.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69679</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69679"/>
		<updated>2012-11-16T23:33:08Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
From the above diagram we can decipher the following things that are: PrototypeManager class is just a manager class that is used to add and retrieve prototypes by an index number; it has the following variable and methods:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• prototypeList variable: It is the collection that stores all the prototypes&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• AddPrototype method: Allows you to add a prototype to the collection and assigning it an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
• GetPrototype method: Allows you to retrieve a prototype from the collection using an index number&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The IPrototype interface specifies the methods that all prototype classes must implement. It has the Clone method that returns an IPrototype interface.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The ConcretePrototype class is the actual prototype class; it implements the IPrototype interface and has the following property and method:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	copyProperty variable holds the information that is prepopulated. If the variable value is changed then the new instances created will have the new value.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
•	Clone method will make a copy of itself and return it. If the copyProperty is a value type (such as int or string) then we can use shallow copy. If the copyProperty is a reference type (such as an object that contains other objects) then we go for deep copy of the variable.&lt;br /&gt;
The key to this pattern is that you will create your first object with the expensive initializations, and then store the values as a prototype in the repository. When you need create the same object again you can just get the copy of the prototype from the repository with all the values already populated. This reduces the performance overhead [12].&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69678</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69678"/>
		<updated>2012-11-16T23:31:54Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.&amp;lt;ref name=&amp;quot;web&amp;quot;&amp;gt;http://www.oodesign.com/factory-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client.&amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Factory.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.&amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot;&amp;gt;http://sourcemaking.com/design_patterns/factory_method&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create. &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;userpagesfactory&amp;quot; /&amp;gt;&lt;br /&gt;
 ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;sourcemakingfact&amp;quot; /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same.&amp;lt;ref name=&amp;quot;ootemplate&amp;quot;&amp;gt;http://www.oodesign.com/template-method-pattern.html&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;Template method pattern is a behavioural design pattern.&amp;lt;ref name=&amp;quot;wikitemplate&amp;quot;&amp;gt;http://en.wikipedia.org/wiki/Template_method_pattern&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt; Template method pattern helps to avoid code duplication and aids in code reuse.&amp;lt;ref name=&amp;quot;userpagestemp&amp;quot;&amp;gt;http://userpages.umbc.edu/~tarr/dp/lectures/Template.pdf&amp;lt;br&amp;gt;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern &amp;lt;ref name=&amp;quot;ootemplate&amp;quot; /&amp;gt;  ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from &amp;lt;ref name=&amp;quot;userpagestemp&amp;quot; /&amp;gt; &lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;br /&gt;
&lt;br /&gt;
We have a look at the UML diagram for the prototype design pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:protypeuml.PNG|650 px|thumb|right|UML Diagram for prototype pattern]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Protypeuml.PNG&amp;diff=69671</id>
		<title>File:Protypeuml.PNG</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Protypeuml.PNG&amp;diff=69671"/>
		<updated>2012-11-16T23:06:40Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69666</id>
		<title>CSC/ECE 517 Fall 2012/ch2b 2w36 av</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2b_2w36_av&amp;diff=69666"/>
		<updated>2012-11-16T22:58:40Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;big&amp;gt;''' Factory Method pattern and the related patterns (Template, Prototype)'''&amp;lt;/big&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Factory Method'''&lt;br /&gt;
&lt;br /&gt;
Factory method pattern is an Object Oriented Programming concept in which objects can be created without specifying the class to which they belong.Factory method pattern implement the concept of using an object to generate other objects.[1]Factory method is thus a  type of creational pattern.  An interface is defined for object creation. However the subclasses decide which class they want to instantiate. Factory methods thus abstract object instantiation from the client. [7]&lt;br /&gt;
&lt;br /&gt;
The new operator is used in languages like Java to create an object. However in this case the object creation details are not encapsulated. Factory method allows a client to request for an object so that the object creation is encapsulated. Factory method uses inheritance for object creation. The superclass has ‘placeholders’ for the steps involved in object creation. The actual details of the object creation are specified in the subclass.[4]&lt;br /&gt;
&lt;br /&gt;
Use of factory method pattern makes the code  more flexible to change. In factory method pattern, interface is used to create an object and the actual instantiation of objects is deferred to subclasses that implement this interface. New classes can be added that implement this interface. In this way it becomes easy to add new concrete classes with minimal changes to the classes that use these objects.[head_first_design_pattern]. Factory method can be used when a class does not know the type of objects that it needs to create[7]&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Factory Method Pattern ===&lt;br /&gt;
[[File:Factoryuml.JPG|650 px|thumb|right|UML Diagram for factory method pattern ]]&lt;br /&gt;
In the UML diagram on the right, Product is the interface for the type of object created by the factory method. The Product interface is implemented by ConcreteProduct. The factory method which returns an object of type Product, is declared in Creator. The factory method is overridden inside ConcreteCreator to return an instance of ConcreteProduct.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from [4]&lt;br /&gt;
&lt;br /&gt;
 public interface ImageReader {&lt;br /&gt;
    public DecodedImage getDecodedImage();&lt;br /&gt;
 }&lt;br /&gt;
 public class GifReader implements ImageReader {&lt;br /&gt;
    public GifReader( InputStream in ) {&lt;br /&gt;
        // check that it's a gif, throw exception if it's not, then if it is decode it.&lt;br /&gt;
    }&lt;br /&gt;
 public DecodedImage getDecodedImage() {&lt;br /&gt;
       return decodedImage;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class JpegReader implements ImageReader {&lt;br /&gt;
    //...&lt;br /&gt;
 }&lt;br /&gt;
In the example above the ImageReader interface is defined. In this interface, a method getDecodedImage is defined that should return a decoded image. However this image may have been encoded in any format for example GIFF or JPEG. Therefore the functionality of actually decoding the image is implemented inside two classes GifReader and JpegReader . In this way, the responsibility of creating objects decoded in the appropriate format has been delegated to the subclass implementing the interface.&lt;br /&gt;
&lt;br /&gt;
=== Template Pattern ===&lt;br /&gt;
Template method pattern is used to specify the format of an algorithm. The basic skeleton of an algorithm is defined in the base class using abstract operations. Subclasses override these abstract operations in order to provide concrete behaviour.  In this way, two different subclasses may have different implementations of the abstract functions, but the overall structure of the algorithm will remain same[8].Template method pattern is a behavioural design pattern[9]. Template method pattern helps to avoid code duplication and aids in code reuse[10]&lt;br /&gt;
&lt;br /&gt;
=== UML Diagram for Template Method Pattern ===&lt;br /&gt;
[[File:Template_method_implementation_-_uml_class_diagram.gif|650 px|thumb|right|UML Diagram for factory method pattern ]]&lt;br /&gt;
In the UML diagram on the right, abstract primitive operations are defined for which the subclasses provide the implementation. Template method is implemented which specifies the structure of the algorithm. The primitive operations are called within this template method. The ConcreteClass provides subclass specific implementation for the primitive operations.&lt;br /&gt;
&lt;br /&gt;
=== Code Example ===&lt;br /&gt;
This example has been taken from [10]&lt;br /&gt;
&lt;br /&gt;
 public abstract class TextDocument {         &lt;br /&gt;
     public final void printPage () {&lt;br /&gt;
       Document document = createDocument();&lt;br /&gt;
       document.printTextHeader();&lt;br /&gt;
       System.out.println(document.body());&lt;br /&gt;
       document.printTextFooter();&lt;br /&gt;
     }&lt;br /&gt;
     public abstract Document createDocument();&lt;br /&gt;
     public abstract void printTextHeader();&lt;br /&gt;
     public abstract void printTextFooter();&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class PlainTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public PlainTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an Plain text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new PlainTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header plain text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header plain text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 public class HtmlTextDocumentBuilder extends TextDocument {&lt;br /&gt;
     public HtmlTextDocumentBuilder(InputStream in){&lt;br /&gt;
     //check that it is an HTML text document or throw error&lt;br /&gt;
     }&lt;br /&gt;
     public Document createDocument()&lt;br /&gt;
     {&lt;br /&gt;
      return new HtmlTextDocument();&lt;br /&gt;
      }	&lt;br /&gt;
     public void printTextHeader () {&lt;br /&gt;
       // Code for header HTML text header here.&lt;br /&gt;
     }&lt;br /&gt;
     public void printTextFooter () {&lt;br /&gt;
       // Code for header HTML text footer here.&lt;br /&gt;
     }&lt;br /&gt;
     ...&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In the above example, two types of text documents are processed, plain text Document and HTML text document. To print any of the document, the procedure to print the document body is the same. However the methods to print the header and the footer are different for both the documents. Therefore they are defined in the abstract class but the specialized implementation is provided in the subclass. printPage() is the template method. Two types of objects are used, PlainTextDocument and HtmlTextDocument. A Factory method createDocument() is called within the Template method printPage() for this purpose.&lt;br /&gt;
&lt;br /&gt;
===Prototype Design Pattern===&lt;br /&gt;
The Prototype pattern creates a new object by cloning an existing object. The client using the prototype object does not need to know what kind of object it deals with as long as the concrete prototype extends or implements the prototype interface or class. The concrete prototype object is responsible for cloning itself and hence returning the cloned object.&lt;br /&gt;
The pattern thus enables a client to create the kind of object required at runtime by selecting the appropriate prototype. The prototype classes are created generically by the client without the client knowing the exact type of the concrete prototype. New concrete prototypes can be added at run-time as long as they are similar to the abstract prototype [11].&lt;br /&gt;
This pattern allows you to avoid expensive initialization routines when you construct objects that are very similar. Also the goal is to minimize the amount of work needed in creating new objects when the initialization routines are expensive. For example, if the initialization routine requires database queries, file look ups, or service calls and you already have other objects in the system that are very similar to the object you are constructing, then the prototype pattern comes into picture and helps you avoid those expensive initializations.&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=69633</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=69633"/>
		<updated>2012-11-16T22:05:07Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*[[CSC/ECE_517_Fall_2012/Table_Of_Contents]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w1 rk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w20 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w5 su]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w6 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w4 aj]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w7 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w8 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w9 av]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w10 pk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w11 ap]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w12 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w14 gv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w17 ir]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w22 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 wi]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w31 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w16 br]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w23 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w24 nr]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w15 rt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w3 pl]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w32 cm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w37 ss]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w67 ks]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w27 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w29 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w33 op]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w19 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w34 vd]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w35 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w30 rp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w58 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w47 sk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w69 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w44 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w45 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w53 kc]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 ar]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w39 sn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w54 go]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w56 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w64 nn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w66 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w42 js]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w46 sm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w71 gs]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w63 dv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w55 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w57 mp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w52 an]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch1b 1w38 nm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w60 ac]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w62 rb]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w29 st]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w3_sm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w30 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w17 pt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w31 up]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w9 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w19 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w26 aj]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w16 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w8 vp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w3 jm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w23 sr]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w11_aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w15 rr]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w33 pv]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w20_aa]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w14_bb]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w21_ap]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w13_sm]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w4_sa]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w25_nr]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w12_sv]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w7_ma]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w6_ar]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w32_mk]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w10_rc]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w70_sm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w67_sk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w40_sn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w22_sk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w-1w65_am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w59_bc]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w60_ns]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w69_as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w39_ka]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2b_2w36_av]]&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67516</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67516"/>
		<updated>2012-10-11T03:14:27Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Generic method definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
  public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Generics====&lt;br /&gt;
&lt;br /&gt;
*At run-time, all generic type information is lost.&lt;br /&gt;
    &lt;br /&gt;
*At run-time, all type parameter instances are converted to/from Object references, meaning that there is a high upcast/downcast overhead when using generics.&lt;br /&gt;
    &lt;br /&gt;
*All instances of generic classes have the exact same static members.&lt;br /&gt;
   &lt;br /&gt;
*It is not possible to throw generic exceptions (generic classes derived from Throwable).&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
* Metaprograms can be difficult to maintain by programmers inexperienced in metaprogramming.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67513</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67513"/>
		<updated>2012-10-11T02:46:27Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Generic method definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
 public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Generics====&lt;br /&gt;
&lt;br /&gt;
*At run-time, all generic type information is lost.&lt;br /&gt;
    &lt;br /&gt;
*At run-time, all type parameter instances are converted to/from Object references, meaning that there is a high upcast/downcast overhead when using generics.&lt;br /&gt;
    &lt;br /&gt;
*All instances of generic classes have the exact same static members.&lt;br /&gt;
   &lt;br /&gt;
*It is not possible to throw generic exceptions (generic classes derived from Throwable).&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
* Metaprograms can be difficult to maintain by programmers inexperienced in metaprogramming.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67405</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67405"/>
		<updated>2012-10-10T20:58:40Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Generics */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Generics====&lt;br /&gt;
&lt;br /&gt;
*At run-time, all generic type information is lost.&lt;br /&gt;
    &lt;br /&gt;
*At run-time, all type parameter instances are converted to/from Object references, meaning that there is a high upcast/downcast overhead when using generics.&lt;br /&gt;
    &lt;br /&gt;
*All instances of generic classes have the exact same static members.&lt;br /&gt;
   &lt;br /&gt;
*It is not possible to throw generic exceptions (generic classes derived from Throwable).&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
* Metaprograms can be difficult to maintain by programmers inexperienced in metaprogramming.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67392</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67392"/>
		<updated>2012-10-10T20:34:43Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Benefits: */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
* Metaprograms can be difficult to maintain by programmers inexperienced in metaprogramming.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67390</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67390"/>
		<updated>2012-10-10T20:33:49Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Metaprogramming: Benefits/Drawbacks */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Metaprogramming can accomplish truly generic code, facilitating code minimization and better maintainability.&lt;br /&gt;
Readability &lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
* Metaprograms can be difficult to maintain by programmers inexperienced in metaprogramming.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67389</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67389"/>
		<updated>2012-10-10T20:30:47Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Drawbacks */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
*Compilation may become slow.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67301</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67301"/>
		<updated>2012-10-08T05:12:19Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Generic Class Definitions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This generic class can be used in the following way:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; grade440 = new Entry&amp;lt;String, String&amp;gt;(&amp;quot;mike&amp;quot;, &amp;quot;A&amp;quot;);&lt;br /&gt;
 Entry&amp;lt;String, Integer&amp;gt; marks440 = new Entry&amp;lt;String, Integer&amp;gt;(&amp;quot;mike&amp;quot;, 100);&lt;br /&gt;
 System.out.println(&amp;quot;grade: &amp;quot; + grade440);&lt;br /&gt;
 System.out.println(&amp;quot;marks: &amp;quot; + marks440);&lt;br /&gt;
&lt;br /&gt;
====Generic method definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic method using the generic class above:&lt;br /&gt;
&lt;br /&gt;
public static &amp;lt;T&amp;gt; Entry&amp;lt;T,T&amp;gt; twice(T value) {&lt;br /&gt;
   return new SimpleImmutableEntry&amp;lt;T,T&amp;gt;(value, value);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
In many cases the user of the method need not indicate the type parameters, as they can be inferred:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
The parameters can be explicitly added if needed:&lt;br /&gt;
&lt;br /&gt;
 Entry&amp;lt;String, String&amp;gt; pair = this.&amp;lt;String&amp;gt;twice(&amp;quot;Hello&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
Generic methods can be defined based on given parameters.&lt;br /&gt;
&lt;br /&gt;
 public &amp;lt;T&amp;gt; T[] toArray(T... elements) {&lt;br /&gt;
   return elements;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67300</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67300"/>
		<updated>2012-10-08T05:01:02Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
====Generic Class Definitions====&lt;br /&gt;
&lt;br /&gt;
Here is an example of a generic class:&lt;br /&gt;
&lt;br /&gt;
 public class Entry&amp;lt;K, V&amp;gt; {&lt;br /&gt;
 &lt;br /&gt;
  private final K key;&lt;br /&gt;
  private final V value;&lt;br /&gt;
 &lt;br /&gt;
  public Entry(K k,V v) {  &lt;br /&gt;
    key = k;&lt;br /&gt;
    value = v;   &lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public K getKey() {&lt;br /&gt;
    return key;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public V getValue() {&lt;br /&gt;
    return value;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  public String toString() { &lt;br /&gt;
    return &amp;quot;(&amp;quot; + key + &amp;quot;, &amp;quot; + value + &amp;quot;)&amp;quot;;  &lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67085</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67085"/>
		<updated>2012-10-04T01:35:12Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Annotations applied to java code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67083</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67083"/>
		<updated>2012-10-04T01:33:37Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Annotations applied to java code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
  public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67082</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67082"/>
		<updated>2012-10-04T01:32:52Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Annotations applied to java code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67080</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67080"/>
		<updated>2012-10-04T01:31:44Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Annotations applied to java code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67073</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67073"/>
		<updated>2012-10-04T01:30:29Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Further Reading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1. http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2. http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3. http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67070</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67070"/>
		<updated>2012-10-04T01:29:25Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Further Reading */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1.http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2.http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3.http://rubysource.com/ruby-metaprogramming-part-i/&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67069</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67069"/>
		<updated>2012-10-04T01:29:03Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
&lt;br /&gt;
==Further Reading==&lt;br /&gt;
&lt;br /&gt;
1.http://c2.com/cgi/wiki?MetaProgramming&lt;br /&gt;
&lt;br /&gt;
2.http://rubylearning.com/blog/2010/11/23/dont-know-metaprogramming-in-ruby/&lt;br /&gt;
&lt;br /&gt;
3.http://rubysource.com/ruby-metaprogramming-part-i/&lt;br /&gt;
&lt;br /&gt;
4.&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67010</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=67010"/>
		<updated>2012-10-04T01:13:47Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Annotations applied to java code */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
This following example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=66991</id>
		<title>CSC/ECE 517 Fall 2012/1w41 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/1w41_as&amp;diff=66991"/>
		<updated>2012-10-04T01:10:54Z</updated>

		<summary type="html">&lt;p&gt;Abhagav: /* Benefits: */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;==Introduction==&lt;br /&gt;
In this page, the concept of meta-programming is discussed. We first give the definition of meta-programming, along with a brief description. Next, we give an overview of the concept of meta-program in general i.e. its evolution and implementation in various languages is discussed. We then focus on the languages in which Meta -programming is prevalent namely Ruby, Java, C, C++ and Python. We then follow it up with the advantages and disadvantages of the same before concluding.&lt;br /&gt;
&lt;br /&gt;
==Definition==&lt;br /&gt;
Meta-programming is the discipline of writing programs that represent and manipulate other programs or themselves. An established example of meta-program is a [http://en.wikipedia.org/wiki/Compiler compiler]. We can also define a meta-program as a program which generates code and writing such programs is called meta-programming. &lt;br /&gt;
This allows programmers to get more work done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation. &lt;br /&gt;
The ability of a programming language to be its own meta-language is called reflection or reflexivity. This reflection ability is a feature that is very valuable to facilitate meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Evolution of Meta-programming== &lt;br /&gt;
Meta-programming was first introduced in Lisp. In Lisp, instead of just programming towards the language, we usually build the language up to our program. This is where the meta-programming comes into picture. For meta-programming purpose, Lisp provides macros as a standard facility to write code that will be directly be read and compiled by the system at run time. &lt;br /&gt;
&lt;br /&gt;
For [http://planet.plt-scheme.org/package-source/dherman/c.plt/3/1/planet-docs/c/index.html Meta programming in C-language],one of the popular examples is the Lex/Yacc system for generation of parsers and lexical scanners. That is, it reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in C. &lt;br /&gt;
&lt;br /&gt;
For [http://www.boostpro.com/mplbook/ Meta programming in C++], it is done with C++ templates i.e., we define the program’s content by writing code that generates it. The code is generally written in between question marks. &lt;br /&gt;
&lt;br /&gt;
Similar programs exist for Java and C#. The general idea, however, is that such an approach can be used anywhere we have a formal specification for which we know how to generate code. &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Prolog Prolog], a generic purpose programming language, which uses the same data structures as the meta-programming and also provides simple clause expansions, is generally used for meta-programming.&lt;br /&gt;
&lt;br /&gt;
==How Meta-programming works==&lt;br /&gt;
Meta-programming usually works in one of three ways. The first way is to expose the internals of the run-time engine to the programming code through [http://en.wikipedia.org/wiki/Application_programming_interface application programming interfaces] (APIs).&lt;br /&gt;
&lt;br /&gt;
The second approach is dynamic execution of expressions that contain programming commands, often composed from strings, but can also be from other methods using arguments and/or context. Thus, &amp;quot;programs can write programs.&amp;quot; &lt;br /&gt;
&lt;br /&gt;
The third way is to step outside the language entirely. General purpose [http://en.wikipedia.org/wiki/Program_transformation program transformation systems], which accept language descriptions and can carry out arbitrary transformations on those languages, are direct implementations of general meta-programming. This allows meta-programming to be applied to virtually any target language without regard to whether that target language has any meta-programming abilities of its own.&lt;br /&gt;
&lt;br /&gt;
==Uses of Meta-programming==&lt;br /&gt;
Let us look at some of the uses of meta-programming:&lt;br /&gt;
&lt;br /&gt;
*The major use of meta-programming is that it pre-generates the code at run-time. For example, if we are writing an application and we want a quick lookup table containing keys and values associated with the keys, we can have the program build the table at startup during runtime. &lt;br /&gt;
&lt;br /&gt;
*It is the key ingredient for [http://en.wikipedia.org/wiki/Domain-specific_language Domain Specific Languages]. That is we use meta-programming to encapsulate domain-specific knowledge. &lt;br /&gt;
&lt;br /&gt;
*Using meta-programming we can easily reduce the cost and time of development for a system by one order of magnitude, while improving the overall quality of the resulting code.&lt;br /&gt;
&lt;br /&gt;
==Meta programming in Ruby== &lt;br /&gt;
Here we discuss about the implementation of meta-programming in a programming language called [http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 Ruby]. We will also discuss about various techniques which help in implementing meta-programming. Ruby is an object-oriented and dynamic language. Ruby is also reflexive i.e., Ruby program can observe and modify its own structure and behavior at runtime. Also in Ruby, code is nothing but data and data is nothing but code. All these features of Ruby make it implement one of its most powerful features called meta-programming efficiently.&lt;br /&gt;
In Ruby, with this meta-programming feature, we can write code that manipulates language constructs like instance variables, classes and modules at runtime.&lt;br /&gt;
In Ruby, the classes (both standard classes and the classes created by us) are never closed i.e., we can always add extra methods to an existing class. All we need to do is open the class to which we want to add additional methods and then define the method we want to add. For instance, consider the following example: &lt;br /&gt;
   a = [1, 2, 3, 4]&lt;br /&gt;
Here ‘a’ is an array and if we want to find the sum of all the elements of the array, we need to open the Array class and add the method to calculate the sum of the array elements. &lt;br /&gt;
   class Array&lt;br /&gt;
      def sum&lt;br /&gt;
       inject{|a,x| a+x}&lt;br /&gt;
      end&lt;br /&gt;
   end&lt;br /&gt;
We can now call method product for the array. &lt;br /&gt;
       a.sum&lt;br /&gt;
       =&amp;gt; 10&lt;br /&gt;
&lt;br /&gt;
In Ruby, we can show as if there were two methods with same name. With this property, we can implement the concept of meta-programming efficiently in Ruby. Suppose, we have a class called Rectangle and it has an initialize method. Here, we can now instantiate this Rectangle by two ways. That is, either by passing in the coordinates of its corners or by passing in any of its corner along with the length and width of the corner. So, in this manner, even though there is only one initialize method, we can act as if there were two.&lt;br /&gt;
   # The Rectangle constructor accepts arguments in either&lt;br /&gt;
   # of the following forms:&lt;br /&gt;
   class Rectangle&lt;br /&gt;
      def initialize(*args)&lt;br /&gt;
         if args.size &amp;lt; 2  || args.size &amp;gt; 3&lt;br /&gt;
            puts 'Sorry wrong number of arguments passed. This method takes either 2 or 3 arguments.'  &lt;br /&gt;
         else&lt;br /&gt;
            puts 'Correct number of arguments passed!!!'&lt;br /&gt;
            if args.size == 2&lt;br /&gt;
               puts 'Two arguments'&lt;br /&gt;
            else&lt;br /&gt;
               puts 'Three arguments'&lt;br /&gt;
            end&lt;br /&gt;
         end&lt;br /&gt;
       end&lt;br /&gt;
   end&lt;br /&gt;
   Rectangle.new([10, 23], 4, 10)&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Three arguements &lt;br /&gt;
   Rectangle.new([10, 23], [14, 13])&lt;br /&gt;
   #=&amp;gt; Correct number of arguements passed!!!&lt;br /&gt;
   #=&amp;gt; Two arguements&lt;br /&gt;
&lt;br /&gt;
===Singleton classes===&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern Singleton classes] are one of the major properties of Ruby which make implementation of meta-programming efficient. Singleton class also called as meta-class or anonymous class is a class that acts as a proxy to the objects of a class.&lt;br /&gt;
In Ruby, any object will have a class of which it is an instance (the class of the object can be found by calling the method class on it). Ruby has a feature where we can add additional methods to an object. So, when this is done, a new anonymous class is created which acts as an intermediate between the object and its actual class. This intermediate class or proxy class is called as a singleton class.&lt;br /&gt;
We can consider the above example of array and finding the sum for this as well.&lt;br /&gt;
&lt;br /&gt;
===Method aliasing=== &lt;br /&gt;
Method aliasing is a technique used in Ruby to implement the concept of meta-programming. The technique that allows us to give aliases or new names to already existing variables, operators and methods is called as method aliasing. It can also be used to wrap an existing method effectively by intercepting any calls and injecting the desired behavior. Here the new reference or the aliasing name may not be a local, instance, constant, or class variable if we are aliasing a variable. &lt;br /&gt;
Using this method or technique we can perform method over riding efficiently and thereby change the behavior of an object or a class. There are two keywords in Ruby which provide this method aliasing. They are alias and alias_method. The following is the syntax for both these keywords: &lt;br /&gt;
       alias        	:new  :old&lt;br /&gt;
       alias_method     :new, :old&lt;br /&gt;
Generally we use alias to give a second name to a method or variable of a class, whereas we use alias_method when we want to assign second name to a method in a Module. So basically, alias keyword takes two arguments as we can see in the syntax. The first argument is the new name or the second name and second argument is the old name or the original name. Let us look at an example that illustrates this technique. Consider the following example: &lt;br /&gt;
    class Array&lt;br /&gt;
     def sum&lt;br /&gt;
         inject {|a, x| a+x }&lt;br /&gt;
     end&lt;br /&gt;
     alias  :newsum:sum&lt;br /&gt;
    end&lt;br /&gt;
    a = Array.new([1, 2, 3, 4])&lt;br /&gt;
    a.newsum   #=&amp;gt; 10&lt;br /&gt;
In this example, we are defining a new method called sum and then aliasing that method with a new name called newsum in the class Array. Now we can call this method with its alias name as above and still the method will be invoked.&lt;br /&gt;
This is how method aliasing can be implementing. We can notice here that, this technique can be used to add new methods and alias those methods for a given class. In this manner we can also change the behavior of the class. Also, we can call the aliasing name of a method inside another method thereby implementing method over riding concept. Consider the following example to illustrate this: &lt;br /&gt;
         class A&lt;br /&gt;
          def method1&lt;br /&gt;
             puts ”This is the main method”&lt;br /&gt;
           end&lt;br /&gt;
           alias :method2 :method1&lt;br /&gt;
           def method1&lt;br /&gt;
              puts “This is not main method&amp;quot;&lt;br /&gt;
              method2&lt;br /&gt;
           end&lt;br /&gt;
         end&lt;br /&gt;
         a = A.new()&lt;br /&gt;
         a.method1&lt;br /&gt;
         =&amp;gt; This is not main method&lt;br /&gt;
         =&amp;gt; This is main method	&lt;br /&gt;
So, in this manner method over riding is done using method aliasing. We can thus say that method aliasing can be used to implement the concept of meta-programming.&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in C++==&lt;br /&gt;
The need for representing meta-information at compile time became apparent during the development of the C++ Standard library. The problems were solved by the traits template idiom. The first article on template meta-programming was published in 1995. The IF&amp;lt;&amp;gt; template was the first control structure in a generic form. &lt;br /&gt;
&lt;br /&gt;
===Support for meta-programming===&lt;br /&gt;
The meta-programming support in C++ is not a designed feature but more or less abuse of C++ compiler. The code of meta-programs is quite peculiar and obscure. There are also limitations for complexity of the meta-programs set by the compilers.&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Different languages provide different levels of reflection. While Smalltalk allows you to directly modify classes or methods by modifying their meta-objects at runtime, Java provides a much lower lever of reflection, mainly suitable for JavaBeans component model and the Remote Method Invocation mechanism. C++ provides even less support for reflection than Java, the most important feature being runtime type-identification (RTTI). There are also reflective extensions available to C++ &lt;br /&gt;
&lt;br /&gt;
===Two-Level Languages===&lt;br /&gt;
An important concept to static meta-programming is a concept of two-level languages.&lt;br /&gt;
Two-level languages contain static code, which is evaluated at compile time, and dynamic code, which is compiled and later executed at runtime. ISO/ANSI C++ contains a template mechanism for defining parameterized classes and functions. This includes type and integral template parameters and partial ad full template specialization. Templates together with other C++ features constitute Turing-complete, compile time sub-language of C++ (and so C++ is a two-level language). Because the sub-language is Turing complete, there are no theoretical limits to what you can implement with it. In practice, there might be technical limitations, such as compiler limits. The main compile-time conditional construct is template specialization: The compiler has to select a matching template out of several alternatives. The compile-time looping construct is template recursion (e.g. a member of class templates used in its own definition.). The compiler has to expand such patterns recursively.&lt;br /&gt;
===Example=== &lt;br /&gt;
Factorial- One of the most common examples of using static code (i.e., code executed at compile time) is computing the factorial &lt;br /&gt;
n! = 1. 2. 3... (n - 1). n of a natural number. A conventional C++ factorial function is as follows &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  int factorial(int n)&lt;br /&gt;
  {&lt;br /&gt;
  return (n==0)? 1: n*factorial(n-1);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The corresponding static code for computing the factorial at compile time is given as follows; RET is used as an abbreviation for a return statement of a conventional function. When the compiler tries to instantiate the structure template Factorial&amp;lt;7&amp;gt; (where n=7). This involves initializing the enumerator RET with Factorial&amp;lt;6&amp;gt;:: RET*7 and the compiler has to instantiate Factorial&amp;lt;6&amp;gt;::RET (and so on). The template specialization matches for n=0 (i.e. Factorial&amp;lt;0&amp;gt;). &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  template&amp;lt;int n&amp;gt;&lt;br /&gt;
  struct Factorial&lt;br /&gt;
  { &lt;br /&gt;
  enum {RET=Factorial&amp;lt;n-1&amp;gt;::RET*n};&lt;br /&gt;
  };&lt;br /&gt;
  // Note: template specialization&lt;br /&gt;
  template&amp;lt;&amp;gt;&lt;br /&gt;
  struct Factorial&amp;lt;0&amp;gt;&lt;br /&gt;
  { &lt;br /&gt;
  enum{RET=1};&lt;br /&gt;
  };&lt;br /&gt;
  // Usage:&lt;br /&gt;
  cout &amp;lt;&amp;lt; &amp;quot;Factorial(7)= &amp;quot; &amp;lt;&amp;lt; Factoral&amp;lt;7&amp;gt;::RET &amp;lt;&amp;lt; endl;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Meta-programming in JAVA==&lt;br /&gt;
&lt;br /&gt;
Java meta-programming mechanisms:&lt;br /&gt;
&lt;br /&gt;
* Reflection&lt;br /&gt;
&lt;br /&gt;
* Generics&lt;br /&gt;
&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
&lt;br /&gt;
===Reflection===&lt;br /&gt;
Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution. Usually this meta-level information is modeled using the general abstraction mechanisms available in the language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.&lt;br /&gt;
&lt;br /&gt;
The following is an example in [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] using the [http://en.wikipedia.org/wiki/Java_package Java package] [http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html java.lang.reflect:]&lt;br /&gt;
&lt;br /&gt;
 // Without reflection&lt;br /&gt;
 new Foo().hello();&lt;br /&gt;
 &lt;br /&gt;
 // With reflection&lt;br /&gt;
 Class&amp;lt;?&amp;gt; clazz = Class.forName(&amp;quot;Foo&amp;quot;);&lt;br /&gt;
 clazz.getMethod(&amp;quot;hello&amp;quot;).invoke(clazz.newInstance());&lt;br /&gt;
&lt;br /&gt;
====Uses of Reflection====&lt;br /&gt;
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. &lt;br /&gt;
&lt;br /&gt;
====Extensibility Features====&lt;br /&gt;
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.&lt;br /&gt;
&lt;br /&gt;
====Class Browsers and Visual Development Environments====&lt;br /&gt;
A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.&lt;br /&gt;
&lt;br /&gt;
====Debuggers and Test Tools====&lt;br /&gt;
Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.&lt;br /&gt;
&lt;br /&gt;
====Drawbacks of Reflection====&lt;br /&gt;
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.&lt;br /&gt;
&lt;br /&gt;
*Performance Overhead&lt;br /&gt;
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in &lt;br /&gt;
sections of code which are called frequently in performance-sensitive applications.&lt;br /&gt;
&lt;br /&gt;
*Security Restrictions&lt;br /&gt;
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important &lt;br /&gt;
consideration for code which has to run in a restricted security context, such as in an Applet.&lt;br /&gt;
&lt;br /&gt;
*Exposure of Internals&lt;br /&gt;
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private &lt;br /&gt;
fields and methods the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may &lt;br /&gt;
destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.&lt;br /&gt;
&lt;br /&gt;
===Generics===&lt;br /&gt;
Generic in Java is added to provide compile time type-safety of code and removing risk of ClassCastException at [http://javarevisited.blogspot.sg/2012/03/what-is-static-and-dynamic-binding-in.html runtime] which was quite frequent error in Java code. Generics allows Java programmer to write more robust and type-safe code.&lt;br /&gt;
&lt;br /&gt;
====Hierarchy and classification====&lt;br /&gt;
As per Java Language Specification:&lt;br /&gt;
&lt;br /&gt;
*A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.&lt;br /&gt;
&lt;br /&gt;
*A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.&lt;br /&gt;
&lt;br /&gt;
*An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.&lt;br /&gt;
&lt;br /&gt;
*A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.&lt;br /&gt;
&lt;br /&gt;
*A constructor can be declared as generic, independently of whether the class that the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface, the interface constructor is generic.&lt;br /&gt;
&lt;br /&gt;
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.&lt;br /&gt;
  &lt;br /&gt;
  List v = new ArrayList();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = (Integer)v.get(0);        // Run time error&lt;br /&gt;
&lt;br /&gt;
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.&lt;br /&gt;
&lt;br /&gt;
Using generics, the above code fragment can be rewritten as follows:&lt;br /&gt;
 &lt;br /&gt;
  List&amp;lt;String&amp;gt; v = new ArrayList&amp;lt;String&amp;gt;();&lt;br /&gt;
  v.add(&amp;quot;test&amp;quot;);&lt;br /&gt;
  Integer i = v.get(0); // (type error)  Compile time error&lt;br /&gt;
&lt;br /&gt;
The type parameter String within the angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.&lt;br /&gt;
&lt;br /&gt;
===Metadata Annotations===&lt;br /&gt;
An annotation, in the [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java computer programming language], is a special form of syntactic [http://en.wikipedia.org/wiki/Metadata metadata] that can be added to [http://en.wikipedia.org/wiki/Java_%28programming_language%29 Java] source code. Classes, methods, variables, parameters and packages may be annotated. Java annotations can be [http://en.wikipedia.org/wiki/Reflection_%28computer_science%29 reflective] in that they can be embedded in [http://en.wikipedia.org/wiki/Class_%28file_format%29 class files] generated by the compiler and may be retained by the Java VM to be made retrievable at [http://en.wikipedia.org/wiki/Run-time run-time].&lt;br /&gt;
&lt;br /&gt;
====Built-In Annotations====&lt;br /&gt;
Java defines a set of annotations that are built into the language. &lt;br /&gt;
&lt;br /&gt;
====Annotations applied to java code====&lt;br /&gt;
&lt;br /&gt;
*@Override - Checks that the function is an override. Causes a compile warning if the function is not found in one of the parent classes.&lt;br /&gt;
&lt;br /&gt;
*@Deprecated - Marks the function as obsolete. Causes a compile warning if the function is used.&lt;br /&gt;
&lt;br /&gt;
*@SuppressWarnings - Instructs the compiler to suppress the [http://en.wikipedia.org/wiki/Compile_time compile time] warnings specified in the annotation parameters&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
This example shows the use of the @Override annotation. It instructs the compiler to check parent classes for matching functions. In this case, an error is generated that the Cat's gettype() function does not in fact override Animal's getType() as desired, but instead declares a new function due to the name mismatch.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Animal {&lt;br /&gt;
 &lt;br /&gt;
    public void speak() {&lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    public String getType() {&lt;br /&gt;
       return &amp;quot;Generic animal&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br/&amp;gt;&lt;br /&gt;
 public class Cat extends Animal {&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public void speak() { // This is a good override.&lt;br /&gt;
       System.out.println(&amp;quot;Meow.&amp;quot;); &lt;br /&gt;
    }&lt;br /&gt;
 &lt;br /&gt;
    @Override&lt;br /&gt;
    public String gettype() { // throws compile warning due to mistyped name.&lt;br /&gt;
       return &amp;quot;Cat&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Metaprogramming: Benefits/Drawbacks==&lt;br /&gt;
&lt;br /&gt;
===Benefits:===&lt;br /&gt;
&lt;br /&gt;
*Simplicity--The biggest benefit of meta-programming is that from a code-base perspective, it keeps things really simple.  Because no code is generated, your classes remain incredibly small.  For the most part, the only code that exists in your classes is custom methods to handle specific business rules and other specific one-off customizations.And in fact, code generation can sometimes be quite daunting for people simply because the generated code increases the size of the codebase, and thus, it would at least feel like the system would be a bit more unwieldy to manage.&lt;br /&gt;
&lt;br /&gt;
*Real-time Changes--Because the analysis is done at runtime, changes to your data model can be reflected in your application at real-time. There is no need to “regenerate” your code as you would with a code generation approach. But of course, this runtime analysis does incur a cost.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming minimizes the code.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming leads to better functionality.&lt;br /&gt;
&lt;br /&gt;
*Meta-programming provides less effort for programmers and reduces the maintenance effort.&lt;br /&gt;
&lt;br /&gt;
*Meta code is generated at compile time. Thus, results faster programs.&lt;br /&gt;
&lt;br /&gt;
===Drawbacks===&lt;br /&gt;
&lt;br /&gt;
*Impossible to debug.&lt;br /&gt;
&lt;br /&gt;
*Hard to trace.&lt;br /&gt;
&lt;br /&gt;
*Ambiguous to some extent.&lt;br /&gt;
&lt;br /&gt;
*Run-time reflection reduces performance.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
1. http://blog.grahampoulter.com/2008/12/code-generation-vs-metaprogramming-in.html&lt;br /&gt;
&lt;br /&gt;
2. http://www.qcodo.com/wiki/article/background/metaprogramming&lt;br /&gt;
&lt;br /&gt;
3. http://code-jam.blogspot.com/2006/07/metaprogramming.html&lt;br /&gt;
&lt;br /&gt;
4. http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29&lt;br /&gt;
&lt;br /&gt;
5. http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html&lt;br /&gt;
&lt;br /&gt;
6. http://en.wikipedia.org/wiki/Generics_in_Java&lt;br /&gt;
&lt;br /&gt;
7. http://tutorials.jenkov.com/java-generics/index.html&lt;br /&gt;
&lt;br /&gt;
8. http://www.tutorialspoint.com/java/java_generics.htm&lt;br /&gt;
&lt;br /&gt;
9. http://javarevisited.blogspot.com/2011/09/generics-java-example-tutorial.html &lt;br /&gt;
&lt;br /&gt;
10. http://en.wikipedia.org/wiki/Java_annotation&lt;br /&gt;
&lt;br /&gt;
11. http://docs.oracle.com/javaee/6/tutorial/doc/girdd.html&lt;br /&gt;
&lt;br /&gt;
12. http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf&lt;br /&gt;
&lt;br /&gt;
13. http://www.ciaranmchale.com/download/java-reflection-explained-simply-manual-8up.pdf&lt;br /&gt;
&lt;br /&gt;
14. http://tutorials.jenkov.com/java-reflection/classes.html&lt;br /&gt;
&lt;br /&gt;
15. http://webcourse.cs.technion.ac.il/236703/Spring2012/ho/WCFiles/7b%20-%20Reflection%20in%20Java.pdf&lt;br /&gt;
&lt;br /&gt;
16. http://docs.oracle.com/javase/tutorial/reflect/index.html&lt;br /&gt;
&lt;br /&gt;
17. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
18. http://media.pragprog.com/titles/ppmetr/introduction.pdf&lt;br /&gt;
&lt;br /&gt;
19. http://www.vanderburg.org/Speaking/Stuff/oscon05.pdf&lt;br /&gt;
&lt;br /&gt;
20. http://www.ibm.com/developerworks/linux/library/l-metaprog1/index.html&lt;br /&gt;
&lt;br /&gt;
21. http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
&lt;br /&gt;
22. http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;/div&gt;</summary>
		<author><name>Abhagav</name></author>
	</entry>
</feed>