<?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=Sanarsal</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=Sanarsal"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Sanarsal"/>
	<updated>2026-06-05T22:07:46Z</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/ch2a_2w18_as&amp;diff=69362</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=69362"/>
		<updated>2012-10-31T23:16:03Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Abstract Factory and Builder Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_Patterns Design Patterns] are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges&amp;lt;ref&amp;gt;(n.d.). .net design patterns. Retrieved from DoFactory website: http://www.dofactory.com/Patterns/Patterns.aspx&amp;lt;/ref&amp;gt;. Design Patterns in Object - Oriented Languages help show the relationship between the different classes and objects in the program.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be categorized as:&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
&lt;br /&gt;
Abstract Factory and Builder Patterns are examples of Creational Patterns.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-abstract-factory Abstract Factory Pattern] provides an interface for creating families of related or dependent objects without specifying their concrete classes&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-builder Builder Pattern] allows for object level access control by acting as a pass through entity or a placeholder object&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;(2012, October 25). Abstract factory pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Abstract Factory Pattern&lt;br /&gt;
! Builder Pattern&lt;br /&gt;
|-&lt;br /&gt;
! To provide an interface for creating families of related or dependent objects without specifying their concrete classes.&lt;br /&gt;
! To separate the construction of complex objects and their representation, thus allowing the same construction process to create different representations.&lt;br /&gt;
|- &lt;br /&gt;
! Used to provide handles to various types of factories that allow the client to create fixed instances of types of classes.&lt;br /&gt;
! Used to provide types of objects and not factories.&lt;br /&gt;
|- &lt;br /&gt;
! Does not allow customization of objects being created - since client may not even be aware of the type of object it gets.&lt;br /&gt;
! Allows customization of objects that are being created.&lt;br /&gt;
|-&lt;br /&gt;
! Creates the object at one go.&lt;br /&gt;
! Creates the object in parts and then returns the whole object to the client.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68655</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68655"/>
		<updated>2012-10-27T00:44:40Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Removed wrong section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_Patterns Design Patterns] are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges&amp;lt;ref&amp;gt;(n.d.). .net design patterns. Retrieved from DoFactory website: http://www.dofactory.com/Patterns/Patterns.aspx&amp;lt;/ref&amp;gt;. A Design Pattern is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in Object - Oriented Languages help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software&amp;lt;ref&amp;gt;(2012, October 10). Design patterns in ruby. Retrieved from Expertiza Wiki website: http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1b_1w42_js#Design_Patterns_in_Ruby&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be categorized as:&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
&lt;br /&gt;
Abstract Factory and Builder Patterns are examples of Creational Patterns.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-abstract-factory Abstract Factory Pattern] provides an interface for creating families of related or dependent objects without specifying their concrete classes&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-builder Builder Pattern] allows for object level access control by acting as a pass through entity or a placeholder object&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;(2012, October 25). Abstract factory pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Abstract Factory Pattern&lt;br /&gt;
! Builder Pattern&lt;br /&gt;
|-&lt;br /&gt;
! To provide an interface for creating families of related or dependent objects without specifying their concrete classes.&lt;br /&gt;
! To separate the construction of complex objects and their representation, thus allowing the same construction process to create different representations.&lt;br /&gt;
|- &lt;br /&gt;
! Used to provide handles to various types of factories that allow the client to create fixed instances of types of classes.&lt;br /&gt;
! Used to provide types of objects and not factories.&lt;br /&gt;
|- &lt;br /&gt;
! Does not allow customization of objects being created - since client may not even be aware of the type of object it gets.&lt;br /&gt;
! Allows customization of objects that are being created.&lt;br /&gt;
|-&lt;br /&gt;
! Creates the object at one go.&lt;br /&gt;
! Creates the object in parts and then returns the whole object to the client.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68653</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68653"/>
		<updated>2012-10-27T00:43:48Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Comparison */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_Patterns Design Patterns] are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges&amp;lt;ref&amp;gt;(n.d.). .net design patterns. Retrieved from DoFactory website: http://www.dofactory.com/Patterns/Patterns.aspx&amp;lt;/ref&amp;gt;. A Design Pattern is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in Object - Oriented Languages help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software&amp;lt;ref&amp;gt;(2012, October 10). Design patterns in ruby. Retrieved from Expertiza Wiki website: http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1b_1w42_js#Design_Patterns_in_Ruby&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be categorized as:&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
&lt;br /&gt;
Abstract Factory and Builder Patterns are examples of Creational Patterns.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-abstract-factory Abstract Factory Pattern] provides an interface for creating families of related or dependent objects without specifying their concrete classes&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-builder Builder Pattern] allows for object level access control by acting as a pass through entity or a placeholder object&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;(2012, October 25). Abstract factory pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
=Comparison of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Abstract Factory Pattern&lt;br /&gt;
! Builder Pattern&lt;br /&gt;
|-&lt;br /&gt;
! To provide an interface for creating families of related or dependent objects without specifying their concrete classes.&lt;br /&gt;
! To separate the construction of complex objects and their representation, thus allowing the same construction process to create different representations.&lt;br /&gt;
|- &lt;br /&gt;
! Used to provide handles to various types of factories that allow the client to create fixed instances of types of classes.&lt;br /&gt;
! Used to provide types of objects and not factories.&lt;br /&gt;
|- &lt;br /&gt;
! Does not allow customization of objects being created - since client may not even be aware of the type of object it gets.&lt;br /&gt;
! Allows customization of objects that are being created.&lt;br /&gt;
|-&lt;br /&gt;
! Creates the object at one go.&lt;br /&gt;
! Creates the object in parts and then returns the whole object to the client.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68629</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68629"/>
		<updated>2012-10-27T00:35:31Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Abstract Factory and Builder Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
[http://en.wikipedia.org/wiki/Design_Patterns Design Patterns] are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges&amp;lt;ref&amp;gt;(n.d.). .net design patterns. Retrieved from DoFactory website: http://www.dofactory.com/Patterns/Patterns.aspx&amp;lt;/ref&amp;gt;. A Design Pattern is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in Object - Oriented Languages help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software&amp;lt;ref&amp;gt;(2012, October 10). Design patterns in ruby. Retrieved from Expertiza Wiki website: http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1b_1w42_js#Design_Patterns_in_Ruby&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Design Patterns can be categorized as:&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
&lt;br /&gt;
Abstract Factory and Builder Patterns are examples of Creational Patterns.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-abstract-factory Abstract Factory Pattern] provides an interface for creating families of related or dependent objects without specifying their concrete classes&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The [http://java.dzone.com/articles/design-patterns-builder Builder Pattern] allows for object level access control by acting as a pass through entity or a placeholder object&amp;lt;ref name=&amp;quot;multiple&amp;quot;&amp;gt;(1995). Design patterns : elements of reusable object-oriented software. Reading, Mass: Addison-Wesley. &amp;lt;/ref&amp;gt;.  &lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;(2012, October 25). Abstract factory pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68574</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68574"/>
		<updated>2012-10-27T00:13:26Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Abstract Factory */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;(2012, October 25). Abstract factory pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68568</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68568"/>
		<updated>2012-10-27T00:12:13Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Examples==&lt;br /&gt;
Let us understand the Builder pattern better with a couple of examples.&lt;br /&gt;
===Ruby===&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;. Suppose a Cook wants to serve Pizzas. A pizza is made of some dough and can a variety of sauses and toppings.&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
In both examples, the scenario required that an object be created by using multiple components. The object can be created in different flavors by varying the components used. The Builder pattern is very useful in these scenarios as it lets us specify the components required and abstracts the details related to implementation.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68522</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68522"/>
		<updated>2012-10-27T00:03:23Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The Director does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68518</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68518"/>
		<updated>2012-10-27T00:02:41Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Engineer'' class which specifies the configuration of ''Computer'' required. The ''Engineer'' directs the ''ComputerBuilder'' on what components must be added.&lt;br /&gt;
&lt;br /&gt;
 class Engineer&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The ''Director'' does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68512</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68512"/>
		<updated>2012-10-27T00:01:11Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Class Diagram */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Director'' class which specifies the configuration of ''Computer'' required.&lt;br /&gt;
&lt;br /&gt;
 class Director&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The ''Director'' does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' or ''PizzaBuilder'' i.e the code which instantiates the ''ComputerBuilder'' or ''PizzaBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68504</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68504"/>
		<updated>2012-10-26T23:59:12Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added java example&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Director'' class which specifies the configuration of ''Computer'' required.&lt;br /&gt;
&lt;br /&gt;
 class Director&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at another example in Java&amp;lt;ref&amp;gt;(2012, October 26). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern#Java&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 /** &amp;quot;Product&amp;quot; */&lt;br /&gt;
 class Pizza {&lt;br /&gt;
    private String dough = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String sauce = &amp;quot;&amp;quot;;&lt;br /&gt;
    private String topping = &amp;quot;&amp;quot;;&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public void setDough(String dough)     { this.dough = dough; }&lt;br /&gt;
    public void setSauce(String sauce)     { this.sauce = sauce; }&lt;br /&gt;
    public void setTopping(String topping) { this.topping = topping; }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
    public String getDough()     { return this.dough; }&lt;br /&gt;
    public String getSauce()     { return this.sauce; }&lt;br /&gt;
    public String getTopping()   { return this.topping; }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Builder&amp;quot; */&lt;br /&gt;
 class PizzaBuilder {&lt;br /&gt;
    private Pizza pizza;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return pizza; }&lt;br /&gt;
    public PizzaBuilder() { pizza = new Pizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public void addDough(String dough)     { pizza.setDough(dough); }&lt;br /&gt;
    public void addSauce(String sauce)     { pizza.setSause(pizza.getSauce() + &amp;quot;, &amp;quot; + sause); }&lt;br /&gt;
    public void addTopping(String topping) { pizza.setTopping(pizza.getTopping() + &amp;quot;, &amp;quot; + topping); }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
 /** &amp;quot;Director&amp;quot; */&lt;br /&gt;
 class Cook {&lt;br /&gt;
    private PizzaBuilder pizzaBuilder;&lt;br /&gt;
 &lt;br /&gt;
    public Pizza getPizza() { return cookTastyPizza(); }&lt;br /&gt;
 &lt;br /&gt;
    public Pizza cookTastyPizza() {&lt;br /&gt;
       pizzaBuilder = new PizzaBuilder();&lt;br /&gt;
       pizzaBuilder.addDough(&amp;quot;Pan Baked&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addSauce(&amp;quot;Ranch&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Olives&amp;quot;);&lt;br /&gt;
       pizzaBuilder.addTopping(&amp;quot;Tomatoes&amp;quot;);&lt;br /&gt;
       return pizzaBuilder.getPizza();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The ''Cook'' is the Director, which uses the ''PizzaBuilder'' to add ingredients to a ''Pizza''. The ''Director'' does not need to know the implementation details of how the ingredients are added to the Pizza (though you'd want a real Cook to know). Only specifying the contents is sufficient.&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' i.e the code which instantiates the ''ComputerBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68372</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68372"/>
		<updated>2012-10-26T22:52:40Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Removed misplaced lines about Director&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Director'' class which specifies the configuration of ''Computer'' required.&lt;br /&gt;
&lt;br /&gt;
 class Director&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at the same example in Java:&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' i.e the code which instantiates the ''ComputerBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68326</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=68326"/>
		<updated>2012-10-26T22:16:03Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Made Ruby and Java subheadings under example&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== UML Diagram ==&lt;br /&gt;
[[File:UML.png]]&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== Ruby ===&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Java ===&lt;br /&gt;
Now let's look at an implementation in Java. The code shows how we can implement a type of button, and clicking the button will display a different message depending on the type of operating system the code is run on. The output should be either &amp;quot;I'm a WinButton&amp;quot; or &amp;quot;I'm an OSXButton&amp;quot; depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory it is given or even what kind of Button that factory creates.&lt;br /&gt;
&lt;br /&gt;
    interface Buttonlike {&lt;br /&gt;
        public void paint();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    interface GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton();&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new WinButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXFactory implements GUIFactorylike {&lt;br /&gt;
        public Buttonlike createButton() {&lt;br /&gt;
            return new OSXButton();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class WinButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm a WinButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class OSXButton implements Buttonlike {&lt;br /&gt;
        public void paint() {&lt;br /&gt;
            System.out.println(&amp;quot;I'm an OSXButton&amp;quot;);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    class Application {&lt;br /&gt;
        public Application(GUIFactorylike factory) {&lt;br /&gt;
            Buttonlike button = factory.createButton();&lt;br /&gt;
            button.paint();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
     &lt;br /&gt;
    public class ApplicationRunner {&lt;br /&gt;
        public static void main(String[] args) {&lt;br /&gt;
            new Application(createOsSpecificFactory());&lt;br /&gt;
        }&lt;br /&gt;
     &lt;br /&gt;
        public static GUIFactorylike createOsSpecificFactory() {&lt;br /&gt;
            int sys = readFromConfigFile(&amp;quot;OS_TYPE&amp;quot;);&lt;br /&gt;
            if (sys == 0) return new WinFactory();&lt;br /&gt;
            else return new OSXFactory();&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. The Director need not know how the object is created. By just asking for the ''Computer'' configuration we need, the ''ComputerBuilder'' class generates the required object. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Director'' class which specifies the configuration of ''Computer'' required.&lt;br /&gt;
&lt;br /&gt;
 class Director&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at the same example in Java:&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' i.e the code which instantiates the ''ComputerBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67659</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67659"/>
		<updated>2012-10-20T23:23:33Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Builder */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Example ==&lt;br /&gt;
Let's say we are creating a Habitat which we populate with trees and animals. However, we need to ensure that the combination of trees and animals makes sense, viz. a client should add Algae and Frog together in the habitat, or Tiger and Tree, but not Tiger and Algae or Frog and Tree. We simply create two factories, one for adding Tigers and Trees and one for adding Frogs and Algae. The object dedicated to creating the compatible set of objects is the abstract factory.&lt;br /&gt;
&lt;br /&gt;
== Ruby ==&lt;br /&gt;
    class Tiger&lt;br /&gt;
      # Tiger specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Tree&lt;br /&gt;
      # Tree specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Frog&lt;br /&gt;
      # Frog specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Algae&lt;br /&gt;
      # Algae specific class implementation&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class JungleOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Tiger.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Tree.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    class Habitat&lt;br /&gt;
      def initialize(number_animals, number_plants, organism_factory)&lt;br /&gt;
        @organism_factory = organism_factory&lt;br /&gt;
    &lt;br /&gt;
        @animals = []&lt;br /&gt;
        number_animals.times do |i|&lt;br /&gt;
          animal = @organism_factory.new_animal(&amp;quot;Animal#{i}&amp;quot;)&lt;br /&gt;
          @animals &amp;lt;&amp;lt; animal&lt;br /&gt;
        end&lt;br /&gt;
    &lt;br /&gt;
        @plants = []&lt;br /&gt;
        number_plants.times do |i|&lt;br /&gt;
          plant = @organism_factory.new_plant(&amp;quot;Plant#{i}&amp;quot;)&lt;br /&gt;
          @plants &amp;lt;&amp;lt; plant&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
We can now feed different abstract factories to our habitat, and also ensure that no illogical combinations of plants and animals exist in our created habitat.&lt;br /&gt;
&lt;br /&gt;
    jungle = Habitat.new(1, 4, JungleOrganismFactory.new)&lt;br /&gt;
    pond = Habitat.new( 2, 4, PondOrganismFactory.new)&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects. The Director need not know how the object is created. By just asking for the ''Computer'' configuration we need, the ''ComputerBuilder'' class generates the required object. &lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer. This is done in the ''Director'' class which specifies the configuration of ''Computer'' required.&lt;br /&gt;
&lt;br /&gt;
 class Director&lt;br /&gt;
  builder = ComputerBuilder.new&lt;br /&gt;
  builder.turbo&lt;br /&gt;
  builder.add_blu_ray(true)&lt;br /&gt;
  builder.add_hard_disk(100000)&lt;br /&gt;
  computer = builder.computer&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at the same example in Java:&lt;br /&gt;
&lt;br /&gt;
==Class Diagram==&lt;br /&gt;
Lets look at the class diagram for the Builder Pattern:&lt;br /&gt;
&lt;br /&gt;
[[File:BuilderPattern.png]]&lt;br /&gt;
&lt;br /&gt;
The client of the ''ComputerBuilder'' i.e the code which instantiates the ''ComputerBuilder'' object is called the [http://sourcemaking.com/design_patterns/builder#permalink-5 Director]. The Builder class creates the complex objects and at the same time hides the implementation details from the Director.&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:BuilderPattern.png&amp;diff=67655</id>
		<title>File:BuilderPattern.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:BuilderPattern.png&amp;diff=67655"/>
		<updated>2012-10-20T23:06:42Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: The client of the builder object is called Director because it directs the builder in constructing the object (called Product).&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;The client of the builder object is called Director because it directs the builder in constructing the object (called Product).&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67651</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67651"/>
		<updated>2012-10-20T23:01:18Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Java and Ruby headings added&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Example ==&lt;br /&gt;
The output will be either &amp;quot;&amp;quot; or &amp;quot;&amp;quot; depending on what kind of Factory is used. As you can see, the client does not know what kind of Factory it is given.&lt;br /&gt;
&lt;br /&gt;
== Ruby ==&lt;br /&gt;
    class PondOrganismFactory&lt;br /&gt;
      def new_animal(name)&lt;br /&gt;
        Frog.new(name)&lt;br /&gt;
      end&lt;br /&gt;
      def new_plant(name)&lt;br /&gt;
        Algae.new(name)&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
==Example==&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. &lt;br /&gt;
&lt;br /&gt;
===Ruby===&lt;br /&gt;
Lets define a ''Computer'' and other related objects in Ruby&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer:&lt;br /&gt;
&lt;br /&gt;
 builder = ComputerBuilder.new&lt;br /&gt;
 builder.turbo&lt;br /&gt;
 builder.add_blu_ray(true)&lt;br /&gt;
 builder.add_hard_disk(100000)&lt;br /&gt;
 computer = builder.computer&lt;br /&gt;
&lt;br /&gt;
===Java===&lt;br /&gt;
Not lets have a look at the same example in Java:&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67648</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67648"/>
		<updated>2012-10-20T22:52:54Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Website reference updated to APA format&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;(2012, October 17). Builder pattern. Retrieved from Wikipedia website: http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;(n.d.). Builder pattern. Retrieved from OODesign website: http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer:&lt;br /&gt;
&lt;br /&gt;
 builder = ComputerBuilder.new&lt;br /&gt;
 builder.turbo&lt;br /&gt;
 builder.add_blu_ray(true)&lt;br /&gt;
 builder.add_hard_disk(100000)&lt;br /&gt;
 computer = builder.computer&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67647</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67647"/>
		<updated>2012-10-20T22:48:08Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Example reference added&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects&amp;lt;ref&amp;gt;Olsen, R. (2007). Easier object construction with the builder. In Design patterns in ruby (pp. 250-253). Addison Wesley. &amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer:&lt;br /&gt;
&lt;br /&gt;
 builder = ComputerBuilder.new&lt;br /&gt;
 builder.turbo&lt;br /&gt;
 builder.add_blu_ray(true)&lt;br /&gt;
 builder.add_hard_disk(100000)&lt;br /&gt;
 computer = builder.computer&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67646</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67646"/>
		<updated>2012-10-20T22:44:39Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: ComputerBuilder Ruby example added&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
The basic purpose of the [http://en.wikipedia.org/wiki/Abstract_factory_pattern Abstract Factory] method Pattern is to &amp;quot;Provide an interface for creating families of related or dependent objects without specifying their concrete classes&amp;quot;.&amp;lt;ref&amp;gt;^ [|Gamma, Erich]; Richard Helm, Ralph Johnson, John M. Vlissides (2009-10-23). &amp;quot;Design Patterns: Abstract Factory&amp;quot; (in English) (HTML). informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16. &amp;quot;Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.&amp;quot;&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Abstract Factory Patterns are used when a client needs to create an instance of a class from a group of similarly related classes. The client does not know (or care) which type of class the client gets an instance of. The type of class returned to the client depends on some condition (and is not of the client's choosing) which is usually stored in some sort of a configuration file. The abstract factory looks up this configuration file then returns the corresponding class to the client.&lt;br /&gt;
&lt;br /&gt;
The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Abstract_factory_pattern&amp;lt;/ref&amp;gt;&lt;br /&gt;
*The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.&lt;br /&gt;
*Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. (The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before – thus insulating the client code from change.) This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
Suppose we have to build a Computer which consists of several components like a hard disk, motherboard, disk drives and display.&lt;br /&gt;
Each of the components can be customized - hard disk can have some specified size, display could be Low-Def or Hi-Def, disk drives could be DVD or Blu-Ray. The motherboard itself has a CPU which could be Dual-Core or Quad-Core. It also has memory of some specified size. Lets define a ''Computer'' and other related objects:&lt;br /&gt;
&lt;br /&gt;
 class Computer&lt;br /&gt;
   attr_accessor :display&lt;br /&gt;
   attr_accessor :motherboard&lt;br /&gt;
   attr_reader   :drives&lt;br /&gt;
   def initialize(display=:low-def, motherboard=Motherboard.new, drives=[])&lt;br /&gt;
     @motherboard = motherboard&lt;br /&gt;
     @drives = drives&lt;br /&gt;
     @display = display&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class CPU&lt;br /&gt;
   # CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class DualCoreCPU &amp;lt; CPU&lt;br /&gt;
   # DualCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class QuadCoreCPU &amp;lt; CPU&lt;br /&gt;
   # QuadCore CPU details...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Motherboard&lt;br /&gt;
  attr_accessor :cpu&lt;br /&gt;
  attr_accessor :memory_size&lt;br /&gt;
  def initialize(cpu=DualCoreCPU.new, memory_size=1000)&lt;br /&gt;
     @cpu = cpu&lt;br /&gt;
     @memory_size = memory_size&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class Drive&lt;br /&gt;
  attr_reader :type # either :hard_disk, :blu_ray or :dvd&lt;br /&gt;
  attr_reader :size # in MB&lt;br /&gt;
  attr_reader :writable # true if this drive is writable&lt;br /&gt;
  def initialize(type, size, writable)&lt;br /&gt;
     @type = type&lt;br /&gt;
     @size = size&lt;br /&gt;
     @writable = writable&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
We can then define a ''ComputerBuilder'' class that lets one specify the configuration of each new Computer object you create and assembles them together.&lt;br /&gt;
&lt;br /&gt;
 class ComputerBuilder&lt;br /&gt;
  attr_reader :computer&lt;br /&gt;
  def initialize&lt;br /&gt;
    @computer = Computer.new&lt;br /&gt;
  end&lt;br /&gt;
  def turbo(has_turbo_cpu=true)&lt;br /&gt;
    @computer.motherboard.cpu = TurboCPU.new&lt;br /&gt;
  end&lt;br /&gt;
  def display=(display)&lt;br /&gt;
    @computer.display=display&lt;br /&gt;
  end&lt;br /&gt;
  def memory_size=(size_in_mb)&lt;br /&gt;
    @computer.motherboard.memory_size = size_in_mb&lt;br /&gt;
  end&lt;br /&gt;
  def add_blu_ray(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:blu_ray, 760, writer)&lt;br /&gt;
  end&lt;br /&gt;
  def add_dvd(writer=false)&lt;br /&gt;
    @computer.drives &amp;lt;&amp;lt; Drive.new(:dvd, 4000, writer)&lt;br /&gt;
  end&lt;br /&gt;
   def add_hard_disk(size_in_mb)&lt;br /&gt;
     @computer.drives &amp;lt;&amp;lt; Drive.new(:hard_disk, size_in_mb, true)&lt;br /&gt;
  end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now the ''ComputerBuilder'' object can be used to specify the configuration needed on the Computer:&lt;br /&gt;
&lt;br /&gt;
 builder = ComputerBuilder.new&lt;br /&gt;
 builder.turbo&lt;br /&gt;
 builder.add_blu_ray(true)&lt;br /&gt;
 builder.add_hard_disk(100000)&lt;br /&gt;
 computer = builder.computer&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67631</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67631"/>
		<updated>2012-10-20T22:07:35Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Changed Heading&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
*--Description--&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67630</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67630"/>
		<updated>2012-10-20T22:06:57Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Builder definition + ref links added&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
*--Description--&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
=Builder=&lt;br /&gt;
The [http://en.wikipedia.org/wiki/Builder_pattern Builder Pattern] is a design pattern that abstracts steps of construction of objects so that different implementations of these steps can construct different representations of objects&amp;lt;ref&amp;gt;http://en.wikipedia.org/wiki/Builder_pattern&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations&amp;lt;ref&amp;gt;http://www.oodesign.com/builder-pattern.html&amp;lt;/ref&amp;gt;. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67624</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67624"/>
		<updated>2012-10-20T21:59:02Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Builder Description&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
*--Description--&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
=Builder=&lt;br /&gt;
Complex applications require complex objects. Complex objects are usually made of sub-objects. These sub-objects generally have their own properties and configurations. For example consider a Car object. The Car object is made of many sub-objects like Steering Wheel, Wheels and Transmission. The Steering Wheel could be hydraulic driven or electronic. The Wheels could be tubeless or tubed. The Transmission could be automatic or manual. So to configure a Car object you will first have to configure the individual components and then put them together to build the Car.&lt;br /&gt;
&lt;br /&gt;
The Builder pattern allows you to build complex objects by specifying only its type and contents and not be worried about the implementation details. As a result different representations can be created using the same set of simple objects.&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67613</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67613"/>
		<updated>2012-10-20T21:08:48Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
*--Description--&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
=Builder=&lt;br /&gt;
--Description--&lt;br /&gt;
*--Java Example--&lt;br /&gt;
*--Ruby Example--&lt;br /&gt;
&lt;br /&gt;
=Comparison=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67610</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67610"/>
		<updated>2012-10-20T20:50:28Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Place holders for abs fact n builder&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
=Abstract Factory=&lt;br /&gt;
&lt;br /&gt;
=Builder=&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67609</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67609"/>
		<updated>2012-10-20T20:49:21Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Creational Pattern overview&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
Creational Patterns are Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67608</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w18 as</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w18_as&amp;diff=67608"/>
		<updated>2012-10-20T20:47:53Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Abstract Fact n Builder first edit&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Abstract Factory and Builder Patterns=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=67606</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=67606"/>
		<updated>2012-10-20T20:44:20Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&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/ch 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 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;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67368</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67368"/>
		<updated>2012-10-10T15:30:26Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added external links for each pattern&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* [http://www.oodesign.com/factory-pattern.html'''''Factory Pattern'''''], which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* [http://www.oodesign.com/abstract-factory-pattern.html'''''Abstract Factory Pattern'''''], which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* [http://www.oodesign.com/builder-pattern.html'''''Builder Pattern'''''], which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* [http://www.oodesign.com/prototype-pattern.html'''''Prototype Pattern'''''], which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* [http://www.oodesign.com/singleton-pattern.html'''''Singleton Pattern'''''], which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* [http://www.oodesign.com/adapter-pattern.html'''''Adapter Pattern'''''], which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* [http://www.oodesign.com/bridge-pattern.html'''''Bridge Pattern'''''], which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* [http://www.oodesign.com/composite-pattern.html'''''Composite Pattern'''''], which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* [http://www.oodesign.com/decorator-pattern.html'''''Decorator Pattern'''''], which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* [http://sourcemaking.com/design_patterns/facade'''''Facade Pattern'''''], which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* [http://www.oodesign.com/flyweight-pattern.html'''''Flyweight Pattern'''''], where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* [http://www.oodesign.com/proxy-pattern.html'''''Proxy Pattern'''''], where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* [http://www.oodesign.com/command-pattern.html'''''Command Pattern'''''], which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* [http://www.oodesign.com/chain-of-responsibility-pattern.html'''''Chain of Responsibility Pattern'''''], where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* [http://www.oodesign.com/interpreter-pattern.html'''''Interpreter Pattern'''''], which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* [http://www.oodesign.com/iterator-pattern.html'''''Iterator Pattern'''''], where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* [http://www.oodesign.com/mediator-pattern.html'''''Mediator Pattern'''''], which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* [http://www.oodesign.com/memento-pattern.html'''''Memento Pattern'''''], which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* [http://www.oodesign.com/observer-pattern.html'''''Observer Pattern'''''], is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* [http://sourcemaking.com/design_patterns/state'''''State Pattern'''''], is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* [http://www.oodesign.com/strategy-pattern.html'''''Strategy Pattern'''''], where Algorithms can be selected on the fly.&lt;br /&gt;
* [http://www.oodesign.com/template-method-pattern.html'''''Template Pattern'''''], which describes the program skeleton of a program.&lt;br /&gt;
* [http://www.oodesign.com/visitor-pattern.html'''''Visitor Pattern'''''], is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - implementation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
As state earlier, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.&amp;lt;ref&amp;gt;(n.d.). Behavioral patterns. Retrieved from SourceMaking website: http://sourcemaking.com/behavioral_patterns&amp;lt;/ref&amp;gt;&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Pattern] is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparison of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parametrization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67336</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67336"/>
		<updated>2012-10-09T01:55:18Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Typo corrected&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Memento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - implementation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
As state earlier, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.&amp;lt;ref&amp;gt;(n.d.). Behavioral patterns. Retrieved from SourceMaking website: http://sourcemaking.com/behavioral_patterns&amp;lt;/ref&amp;gt;&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Pattern] is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparison of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parametrization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67335</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67335"/>
		<updated>2012-10-09T01:51:02Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Typos corrected&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Memento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - implementation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
As state earlier, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.&amp;lt;ref&amp;gt;(n.d.). Behavioral patterns. Retrieved from SourceMaking website: http://sourcemaking.com/behavioral_patterns&amp;lt;/ref&amp;gt;&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Pattern] is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparison of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67288</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67288"/>
		<updated>2012-10-05T04:52:44Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Add link for command pattern&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
As state earlier, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.&amp;lt;ref&amp;gt;(n.d.). Behavioral patterns. Retrieved from SourceMaking website: http://sourcemaking.com/behavioral_patterns&amp;lt;/ref&amp;gt;&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Pattern] is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67287</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67287"/>
		<updated>2012-10-05T04:46:03Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added definition for Beh Pat&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
As state earlier, behavioral design patterns are design patterns that identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.&amp;lt;ref&amp;gt;(n.d.). Behavioral patterns. Retrieved from SourceMaking website: http://sourcemaking.com/behavioral_patterns&amp;lt;/ref&amp;gt;&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67285</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67285"/>
		<updated>2012-10-05T00:55:05Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added Structural Patterns description&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
Structural Patterns are Design Patterns which describe how Classes and Methods can be combined to form larger, more complex structures. They involve connection between objects. &lt;br /&gt;
&lt;br /&gt;
In some sense, structural patterns are similar to the simpler concept of data structures &amp;lt;ref&amp;gt;(n.d.). What is a structural pattern? Retrieved from Gof Patterns - Gang of Four Patterns website: http://www.gofpatterns.com/design-patterns/module5/structural-design-pattern.php&amp;lt;/ref&amp;gt;. &lt;br /&gt;
&lt;br /&gt;
However, structural design patterns also specify the methods that connect objects, not merely the references between them. Furthermore, data structures are fairly static entities. They only describe how data is arranged in the structure. A structural design pattern also describes how data moves through the pattern.&lt;br /&gt;
&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67284</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67284"/>
		<updated>2012-10-05T00:43:56Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Proper reference added&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;Stelting, S. (2002). Creational patterns. In Applied java patterns (p. 5). Palo Alto, California: Sun Microsystems. Retrieved from www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67283</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67283"/>
		<updated>2012-10-05T00:32:10Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added description for Creational Pattern&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
Creational Patterns and Design Patterns that somehow control the mechanism by which objects are created. They generally help to provide the following capabilities &amp;lt;ref&amp;gt;www.pearsonhighered.com/samplechapter/0130935387.pdf&amp;lt;/ref&amp;gt;:&lt;br /&gt;
* Generic instantiation – This allows objects to be created in a system without having to identify a specific class type in code.&lt;br /&gt;
* Simplicity – Some of the patterns make object creation easier, so callers will not have to write large, complex code to instantiate an object.&lt;br /&gt;
* Creation constraints – Some patterns enforce constraints on the type or number of objects that can be created within a system. The Singleton Pattern is an example of this type.&lt;br /&gt;
&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67165</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67165"/>
		<updated>2012-10-04T02:09:23Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added 2011 Wiki reference&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;br /&gt;
The old wiki can be found at http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch4_4h_sv&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67141</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67141"/>
		<updated>2012-10-04T02:02:18Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Removed redundant spaces&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, gif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test formatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 if(type == :HTML)&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 else&lt;br /&gt;
 report = Report.new(PlainTextFormatter.new) #formatter type changed to Plain Text Formatter&lt;br /&gt;
  &lt;br /&gt;
 report.output_report # HTML/Plaintext (depends on type variable) Formatter method&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
The GoF call this “pull the algorithm out into a separate object” technique the Strategy pattern (above Figure). The context class is the class that uses Strategy encapsulation. The Strategy1 and Strategy2 are strategies that get actually chosen by context class.&lt;br /&gt;
The key idea underlying the Strategy pattern is to define a family of objects, the strategies, which all do the same thing— in given example, format the report. Not only does each strategy object perform the same job, but all of the objects support exactly the same interface. In given example, both of the strategy objects support the output_report method.&lt;br /&gt;
For more on Strategy Pattern, read the reference book&amp;lt;ref name = 'multiple'&amp;gt;Olsen, R. (2007). Chapter: 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67057</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=67057"/>
		<updated>2012-10-04T01:24:28Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Comparsion of the different Design Patterns */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref&amp;gt;Olsen, R. (2007). 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          #Initialize title and text&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
    end&lt;br /&gt;
 &lt;br /&gt;
 class Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   raise 'Abstract method called'&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class HTMLFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report( title, text )&lt;br /&gt;
   puts('&amp;lt;html&amp;gt;')&lt;br /&gt;
   #More HTML formatting code&lt;br /&gt;
   puts('&amp;lt;/html&amp;gt;')&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 class PlainTextFormatter &amp;lt; Formatter&lt;br /&gt;
  def output_report(title, text)&lt;br /&gt;
    #More Plain Test Fromatting code&lt;br /&gt;
    puts(line)&lt;br /&gt;
  end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The above snippet depicts the structure of the Report class, Formatter class(super class), HtmlFormatter class and PlainTextFormatter class(subclasses of Formatter class). The Report class' initialize method invokes the particular formatter class depending upon the formatter specified. These formatter invocations are not specified in advance, hence the Report class has to choose the required formatter function at the run time. &lt;br /&gt;
&lt;br /&gt;
 report = Report.new(HTMLFormatter.new) #HTML Formatter&lt;br /&gt;
 report.output_report #HTML Formatter method&lt;br /&gt;
 &lt;br /&gt;
 report.formatter = PlainTextFormatter.new #formatter type changed to Plain Text Formatter&lt;br /&gt;
 report.output_report #Plain Text Formatter method&lt;br /&gt;
&lt;br /&gt;
The Strategy pattern is based on composition and delegation, rather than on inheritance, hence it is easy to switch strategies at runtime. &lt;br /&gt;
Thus the path or strategy chosen is based on the formatter invocation on runtime.Therefore, the algorithm that will be selected for displaying the text, is decided at run time.&lt;br /&gt;
&lt;br /&gt;
Illustrated below is the class diagram of Strategy Pattern Design:&lt;br /&gt;
&lt;br /&gt;
[[File:Strategy_class_diagram.jpg]]&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66913</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66913"/>
		<updated>2012-10-04T00:49:00Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Making differences between command and strategy a sub section of Behavioral Patterns&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref&amp;gt;Olsen, R. (2007). 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
==Differences between Command and Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66909</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66909"/>
		<updated>2012-10-04T00:46:15Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Add wiki citation for closures&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2012/ch1_1w32_cm Closures] and [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref&amp;gt;Olsen, R. (2007). 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66901</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66901"/>
		<updated>2012-10-04T00:42:46Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Pluralize Creational Pattern&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Patterns=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Closures and Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref&amp;gt;Olsen, R. (2007). 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66893</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66893"/>
		<updated>2012-10-04T00:40:10Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Deleting closures and patterns section&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Closures and Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. A case statement can be used to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data, where selection of a validation algorithm is based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. An example&amp;lt;ref&amp;gt;Olsen, R. (2007). 4. replacing the algorithm with the strategy. In Design patterns in ruby (pp. 78-109). Addison Wesley. &amp;lt;/ref&amp;gt; of the Strategy Pattern which deals with formatting styles of the report:&lt;br /&gt;
&lt;br /&gt;
 class Report&lt;br /&gt;
     attr_reader :title, :text&lt;br /&gt;
     attr_accessor :formatter&lt;br /&gt;
&lt;br /&gt;
     def initialize(formatter)&lt;br /&gt;
          @formatter = formatter&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66874</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66874"/>
		<updated>2012-10-04T00:35:07Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Changed reference to APA 6 style&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;Singleton pattern - impelmentation. In Oodesign. Retrieved from http://www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Closures and Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66844</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66844"/>
		<updated>2012-10-04T00:25:00Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Command Pattern example changed, cleaned up&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
Illustrated below is the syntax of using singleton in Ruby:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 r.val = 5&lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 s.val = 6&lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
The class diagram&amp;lt;ref&amp;gt;www.oodesign.com/singleton-pattern.html&amp;lt;/ref&amp;gt; for Singleton pattern is illustrated below:&lt;br /&gt;
&lt;br /&gt;
[[File:Singleton implementation - uml class diagram.gif]]&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern defines a getInstance() operation which exposes the unique instance which is accessed by the clients. The getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.&lt;br /&gt;
For more details, follow this [http://www.oodesign.com/singleton-pattern.html link]&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. But sometimes code must be reused at an even finer level. For example, Sometimes one might need to store bunch of code to be used by a peer or at a later stage. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&lt;br /&gt;
Command Pattern is useful in such cases. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage.&lt;br /&gt;
&lt;br /&gt;
Lets consider a simple example of a GUI button that can be configured to do a variety of actions.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 147-148). Addison Wesley.&amp;lt;/ref&amp;gt; These actions could be saving data to database, making a network connection, navigating to another page, etc.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
     &lt;br /&gt;
   end &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   # &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     #&lt;br /&gt;
     # Do some action&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Without the use of the Command Pattern, we could implement a solution here by inheriting the ''UserButton'' into subclasses like ''DatabaseButton'', ''NetworkButton'', etc. For example:&lt;br /&gt;
&lt;br /&gt;
 class DatabaseButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize()&lt;br /&gt;
 &lt;br /&gt;
   end&lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
   def on_button_push&lt;br /&gt;
     # &lt;br /&gt;
     # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
     #&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
This is however a tedious and rigid solution. If suppose on certain button clicks you only wanted to update the database value and not insert. You would either have to create a new subclass with this functionality or check for which operation is required in the on_button_push method and execute separate queries.&lt;br /&gt;
&lt;br /&gt;
The Command Pattern provides an easier way to implement this. The simplest way to implement the Command Pattern in Ruby is through the use of [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object] with [http://www.elonflegenheimer.com/2012/07/08/understanding-ruby-closures.html Closures and Blocks]. &lt;br /&gt;
&lt;br /&gt;
Consider the following definition for the ''UserButton'' class.&lt;br /&gt;
&lt;br /&gt;
 class UserButton&lt;br /&gt;
   attr_accessor :command&lt;br /&gt;
   def initialize(&amp;amp;block)&lt;br /&gt;
     @command = block&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   #&lt;br /&gt;
   # Button rendering and management code&lt;br /&gt;
   #&lt;br /&gt;
 &lt;br /&gt;
   def on_button_push&lt;br /&gt;
     @command.call if @command&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Here the ''@command'' instance variable is a Proc object. In simple terms, it is a chunk of code that can be executed with the ''call'' method.&lt;br /&gt;
&lt;br /&gt;
To instantiate a ''UserButton'' for database insertion, a code block is passed when the object is created.&lt;br /&gt;
&lt;br /&gt;
 new_button = UserButton.new do&lt;br /&gt;
   # &lt;br /&gt;
   # Database operations like InsertIntoDatabase(column, value)&lt;br /&gt;
   # or&lt;br /&gt;
   # Network link creation&lt;br /&gt;
   # or&lt;br /&gt;
   # Navigate to another page&lt;br /&gt;
   #&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The class diagram for the Command Pattern is fairly simple. It consists of a number of classes which share the same interface.&lt;br /&gt;
[[File:Class Diagram - Command Pattern.png]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
An interesting usage of the command pattern is to implement the Undo functionality.&amp;lt;ref&amp;gt;Olsen, R. (2007). Getting things done with commands. In Design patterns in ruby (pp. 151-153). Addison Wesley. &amp;lt;/ref&amp;gt; This requires definition of a unexecute method which undoes the actions done in the execute method. A code example can be found [http://www.java2s.com/Code/Ruby/Design-Patterns/UndobyaCommand.htm here.].&lt;br /&gt;
&lt;br /&gt;
==Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_Diagram_-_Command_Pattern.png&amp;diff=66838</id>
		<title>File:Class Diagram - Command Pattern.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_Diagram_-_Command_Pattern.png&amp;diff=66838"/>
		<updated>2012-10-04T00:22:19Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Command Pattern consists of a number of classes that share a common interface.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Command Pattern consists of a number of classes that share a common interface.&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66649</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66649"/>
		<updated>2012-10-03T23:09:21Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''', which represents a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', which adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', which creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''', where a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''', where a class functions as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''', where command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', which implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''', where iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''', is similar to Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object. &lt;br /&gt;
* '''''State Pattern''''', is a clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''', where Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''', is a way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/singleton-pattern.html Singleton pattern] is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance.For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.&lt;br /&gt;
The Singleton pattern is available as a '''mixin''' in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Registry&lt;br /&gt;
   include Singleton&lt;br /&gt;
   attr_accessor :val&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
 r = Registry.new #throws a NoMethodError as the &amp;quot;new&amp;quot; method is private&lt;br /&gt;
 &lt;br /&gt;
 r = Registry.instance&lt;br /&gt;
 &lt;br /&gt;
 r.val = 5&lt;br /&gt;
 &lt;br /&gt;
 s = Registry.instance # a new reference to the existing object is created. &lt;br /&gt;
 &lt;br /&gt;
 puts s.val &amp;gt;&amp;gt; 5&lt;br /&gt;
 &lt;br /&gt;
 s.val = 6&lt;br /&gt;
 &lt;br /&gt;
 puts r.val &amp;gt;&amp;gt; 6&lt;br /&gt;
 &lt;br /&gt;
 s.dup &amp;gt;&amp;gt; TypeError: can’t duplicate instance of singleton Registry&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
Singletons can also be created without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialized&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;instance&amp;quot; method is defined. The &amp;quot;new&amp;quot; method is made 'private'. This makes sure that objects of the Single_ton cannot be created.&lt;br /&gt;
&lt;br /&gt;
 puts Single_ton.instance  &amp;gt;&amp;gt;  &amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something &amp;gt;&amp;gt; This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that the class 'behaves' like a singleton.&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. What if we need a more finer to do it.For example, Sometimes one might need to store bunch of code to be used by a peer or himself at a later point. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Patterns] lends itself to our use at this point. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage. And of course, this is implemented with the use of procs in Ruby.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
This is how command pattern is usually implemented. We have a class which holds the commands as a [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object]. And whenever it is to be called, 'call' is used to execute that proc.&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
   def initialize(input)&lt;br /&gt;
     @local_proc = input &lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   def return_proc&lt;br /&gt;
    @local_proc&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we have a class that stores a command. Now let us create a 'command'. &lt;br /&gt;
&lt;br /&gt;
 myProc = proc{ puts 8 }&lt;br /&gt;
&lt;br /&gt;
Now we have a proc object that we want to use.&lt;br /&gt;
&lt;br /&gt;
 obj = Command.new(myProc)&lt;br /&gt;
 obj.return_proc.call&lt;br /&gt;
 8&lt;br /&gt;
&lt;br /&gt;
Then we create an object storing myProc inside it. Then we use the object to return the proc and use 'call' on it to execute it. One could also create an array of commands by simply creating an array of Command objects and storing the proc in them. &amp;lt;br&amp;gt; &lt;br /&gt;
&lt;br /&gt;
One important use of the Command Pattern is to enable the client undo what he has already done, or redo what has been undone by the user. This is done by maintaining a history of the commands executed. As and when the user makes changes, the system creates command after command, executing each command immediately to effect the change. Every undo - able command holds two methods - the execute and the unexecute method.&lt;br /&gt;
The commands are stored in a list and when the user decides to undo a change, the last command on the list is executed to undo the change. The changes can be undone, by going back the history of commands. The redo is done in the similar way where the the commands are re-executed beginning from the last change that what undone to reapply the changes undone. A simple example of the undo - redo use of a Command Pattern is a Calculator with many undo - redo options.&lt;br /&gt;
&lt;br /&gt;
'''''This is not much use without a code example'''''&lt;br /&gt;
&lt;br /&gt;
==Algorithm Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66440</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66440"/>
		<updated>2012-10-03T09:42:56Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''': a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''': a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''': a class functioning as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''': Command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''': Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''': Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object &lt;br /&gt;
* '''''State Pattern''''': A clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''': Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''': A way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
The first design pattern one should know about is the [http://www.oodesign.com/singleton-pattern.html Singleton patterns]. It is basically the case, where the Class can instantiate only one object, which is globally available. &lt;br /&gt;
&lt;br /&gt;
'''''Need better definition.'''''&lt;br /&gt;
&lt;br /&gt;
Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Example&lt;br /&gt;
     include Singleton&lt;br /&gt;
     ...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
It could be noticed that one must 'require' a module called 'singleton' and include the module within the class.&lt;br /&gt;
This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,&lt;br /&gt;
&lt;br /&gt;
  raisesError = Example.new&lt;br /&gt;
  ruby-1.9.2-p290 :026 &amp;gt; raisesError = Example.new&lt;br /&gt;
  NoMethodError: private method `new' called for Example:Class&lt;br /&gt;
&lt;br /&gt;
We will soon find out we are greeted with the NoMethodError( Some kind of an error is expected ). So how do we use a singleton pattern? We create an instance of it using the keyword 'instance'&lt;br /&gt;
 &lt;br /&gt;
''''''What is meant by Some kind of error is expected? Content here is good, will need to rephrase.''''''&lt;br /&gt;
&lt;br /&gt;
 a = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt; &lt;br /&gt;
 b = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above illustrates how to create the instance of the Singleton class. It also illustrates another point. Even though two 'instances' have supposedly been created, both of them happen to contain reference to the same object. &lt;br /&gt;
This further proves that only one object can be created for a Singleton.&amp;lt;BR&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''''Rephrase again. Not formal enough'''''&lt;br /&gt;
&lt;br /&gt;
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialised&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;.instance&amp;quot; method is defined. One more thing to notice is that, &amp;quot;new&amp;quot; method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.&lt;br /&gt;
&lt;br /&gt;
 Single_ton.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something&lt;br /&gt;
 This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that our class 'behaves' like a singleton. We have a '.instance' method defined and it works.&lt;br /&gt;
The method could be accessed by accessing the lone object inside the class.&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern is useful in situations where serialization is desirable, example logging, communication and database access etc. In these cases, only a single instance of the class is created which accesses and modifies the methods of the class. This ensures safety and also make the single instance responsible for the class.&amp;lt;br&amp;gt;&lt;br /&gt;
[http://c2.com/cgi/wiki?SingletonPattern Here ] is more to read on Singleton patterns.&lt;br /&gt;
&lt;br /&gt;
'''''Feel like there's some flab in the Singleton section that we can cut. Also could think of adding subsections for Default Implemenation, Custom Implementation, Uses etc.'''''&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Consider a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose a string is to be encrypted instead of a file. To be able to use the same ''Encrypter'' class an object is required that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, lets define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. What if we need a more finer to do it.For example, Sometimes one might need to store bunch of code to be used by a peer or himself at a later point. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Patterns] lends itself to our use at this point. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage. And of course, this is implemented with the use of procs in Ruby.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
This is how command pattern is usually implemented. We have a class which holds the commands as a [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object]. And whenever it is to be called, 'call' is used to execute that proc.&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
   def initialize(input)&lt;br /&gt;
     @local_proc = input &lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   def return_proc&lt;br /&gt;
    @local_proc&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we have a class that stores a command. Now let us create a 'command'. &lt;br /&gt;
&lt;br /&gt;
 myProc = proc{ puts 8 }&lt;br /&gt;
&lt;br /&gt;
Now we have a proc object that we want to use.&lt;br /&gt;
&lt;br /&gt;
 obj = Command.new(myProc)&lt;br /&gt;
 obj.return_proc.call&lt;br /&gt;
 8&lt;br /&gt;
&lt;br /&gt;
Then we create an object storing myProc inside it. Then we use the object to return the proc and use 'call' on it to execute it. One could also create an array of commands by simply creating an array of Command objects and storing the proc in them. &amp;lt;br&amp;gt; &lt;br /&gt;
&lt;br /&gt;
One important use of the Command Pattern is to enable the client undo what he has already done, or redo what has been undone by the user. This is done by maintaining a history of the commands executed. As and when the user makes changes, the system creates command after command, executing each command immediately to effect the change. Every undo - able command holds two methods - the execute and the unexecute method.&lt;br /&gt;
The commands are stored in a list and when the user decides to undo a change, the last command on the list is executed to undo the change. The changes can be undone, by going back the history of commands. The redo is done in the similar way where the the commands are re-executed beginning from the last change that what undone to reapply the changes undone. A simple example of the undo - redo use of a Command Pattern is a Calculator with many undo - redo options.&lt;br /&gt;
&lt;br /&gt;
'''''This is not much use without a code example'''''&lt;br /&gt;
&lt;br /&gt;
==Algorithm Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66439</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66439"/>
		<updated>2012-10-03T09:31:12Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Design Patterns In Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''': a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''': a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''': a class functioning as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''': Command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''': Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''': Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object &lt;br /&gt;
* '''''State Pattern''''': A clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''': Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''': A way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
The first design pattern one should know about is the [http://www.oodesign.com/singleton-pattern.html Singleton patterns]. It is basically the case, where the Class can instantiate only one object, which is globally available. &lt;br /&gt;
&lt;br /&gt;
'''''Need better definition.'''''&lt;br /&gt;
&lt;br /&gt;
Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Example&lt;br /&gt;
     include Singleton&lt;br /&gt;
     ...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
It could be noticed that one must 'require' a module called 'singleton' and include the module within the class.&lt;br /&gt;
This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,&lt;br /&gt;
&lt;br /&gt;
  raisesError = Example.new&lt;br /&gt;
  ruby-1.9.2-p290 :026 &amp;gt; raisesError = Example.new&lt;br /&gt;
  NoMethodError: private method `new' called for Example:Class&lt;br /&gt;
&lt;br /&gt;
We will soon find out we are greeted with the NoMethodError( Some kind of an error is expected ). So how do we use a singleton pattern? We create an instance of it using the keyword 'instance'&lt;br /&gt;
 &lt;br /&gt;
''''''What is meant by Some kind of error is expected? Content here is good, will need to rephrase.''''''&lt;br /&gt;
&lt;br /&gt;
 a = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt; &lt;br /&gt;
 b = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above illustrates how to create the instance of the Singleton class. It also illustrates another point. Even though two 'instances' have supposedly been created, both of them happen to contain reference to the same object. &lt;br /&gt;
This further proves that only one object can be created for a Singleton.&amp;lt;BR&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''''Rephrase again. Not formal enough'''''&lt;br /&gt;
&lt;br /&gt;
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialised&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;.instance&amp;quot; method is defined. One more thing to notice is that, &amp;quot;new&amp;quot; method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.&lt;br /&gt;
&lt;br /&gt;
 Single_ton.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something&lt;br /&gt;
 This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that our class 'behaves' like a singleton. We have a '.instance' method defined and it works.&lt;br /&gt;
The method could be accessed by accessing the lone object inside the class.&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern is useful in situations where serialization is desirable, example logging, communication and database access etc. In these cases, only a single instance of the class is created which accesses and modifies the methods of the class. This ensures safety and also make the single instance responsible for the class.&amp;lt;br&amp;gt;&lt;br /&gt;
[http://c2.com/cgi/wiki?SingletonPattern Here ] is more to read on Singleton patterns.&lt;br /&gt;
&lt;br /&gt;
'''''Feel like there's some flab in the Singleton section that we can cut. Also could think of adding subsections for Default Implemenation, Custom Implementation, Uses etc.'''''&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose we want to encrypt a string instead of a file. To be able to use the same ''Encrypter'' class we require an object that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, we will define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. What if we need a more finer to do it.For example, Sometimes one might need to store bunch of code to be used by a peer or himself at a later point. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Patterns] lends itself to our use at this point. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage. And of course, this is implemented with the use of procs in Ruby.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
This is how command pattern is usually implemented. We have a class which holds the commands as a [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object]. And whenever it is to be called, 'call' is used to execute that proc.&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
   def initialize(input)&lt;br /&gt;
     @local_proc = input &lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   def return_proc&lt;br /&gt;
    @local_proc&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we have a class that stores a command. Now let us create a 'command'. &lt;br /&gt;
&lt;br /&gt;
 myProc = proc{ puts 8 }&lt;br /&gt;
&lt;br /&gt;
Now we have a proc object that we want to use.&lt;br /&gt;
&lt;br /&gt;
 obj = Command.new(myProc)&lt;br /&gt;
 obj.return_proc.call&lt;br /&gt;
 8&lt;br /&gt;
&lt;br /&gt;
Then we create an object storing myProc inside it. Then we use the object to return the proc and use 'call' on it to execute it. One could also create an array of commands by simply creating an array of Command objects and storing the proc in them. &amp;lt;br&amp;gt; &lt;br /&gt;
&lt;br /&gt;
One important use of the Command Pattern is to enable the client undo what he has already done, or redo what has been undone by the user. This is done by maintaining a history of the commands executed. As and when the user makes changes, the system creates command after command, executing each command immediately to effect the change. Every undo - able command holds two methods - the execute and the unexecute method.&lt;br /&gt;
The commands are stored in a list and when the user decides to undo a change, the last command on the list is executed to undo the change. The changes can be undone, by going back the history of commands. The redo is done in the similar way where the the commands are re-executed beginning from the last change that what undone to reapply the changes undone. A simple example of the undo - redo use of a Command Pattern is a Calculator with many undo - redo options.&lt;br /&gt;
&lt;br /&gt;
'''''This is not much use without a code example'''''&lt;br /&gt;
&lt;br /&gt;
==Algorithm Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
* [http://www.oodesign.com Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://c2c.com More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Singleton_pattern Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
* [http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx Command Pattern]&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&amp;lt;references /&amp;gt;&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66438</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66438"/>
		<updated>2012-10-03T09:14:05Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: /* Adapter Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Factory Pattern''''', which allows a class to defer instantiation to subclasses. &lt;br /&gt;
* '''''Abstract Factory Pattern''''', which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.&lt;br /&gt;
* '''''Builder Pattern''''', which separates the construction of a complex object from its representation so that the same construction process can create different representation. &lt;br /&gt;
* '''''Prototype Pattern''''', which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype. &lt;br /&gt;
* '''''Singleton Pattern''''', which ensures that only one instance of a class is created and provides a global access point to the object. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Pattern''''', which 'adapts' one interface for a class into one that a client expects.&lt;br /&gt;
* '''''Bridge Pattern''''', which decouples an abstraction from its implementation so that the two can vary independently.&lt;br /&gt;
* '''''Composite Pattern''''': a tree structure of objects where every object has the same interface.&lt;br /&gt;
* '''''Decorator Pattern''''', adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes&lt;br /&gt;
* '''''Facade Pattern''''', creates a simplified interface of an existing interface to ease usage for common tasks.&lt;br /&gt;
* '''''Flyweight Pattern''''': a high quantity of objects share a common properties object to save space.&lt;br /&gt;
* '''''Proxy Pattern''''': a class functioning as an interface to another thing.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Chain of Responsibility Pattern''''': Command objects are handled or passed on to other objects by logic-containing processing objects.&lt;br /&gt;
* '''''Interpreter Pattern''''', implements a specialized computer language to rapidly solve a specific set of problems.&lt;br /&gt;
* '''''Iterator Pattern''''': Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.&lt;br /&gt;
* '''''Mediator Pattern''''', which provides a unified interface to a set of interfaces in a subsystem.&lt;br /&gt;
* '''''Momento Pattern''''', which provides the ability to restore an object to its previous state (rollback).&lt;br /&gt;
* '''''Observer Pattern''''': Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object &lt;br /&gt;
* '''''State Pattern''''': A clean way for an object to partially change its type at runtime.&lt;br /&gt;
* '''''Strategy Pattern''''': Algorithms can be selected on the fly.&lt;br /&gt;
* '''''Template Pattern''''', which describes the program skeleton of a program.&lt;br /&gt;
* '''''Visitor Pattern''''': A way to separate an algorithm from an object.&lt;br /&gt;
&lt;br /&gt;
Some of the Patterns that are more commonly used with Ruby are explained below.&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
The first design pattern one should know about is the [http://www.oodesign.com/singleton-pattern.html Singleton patterns]. It is basically the case, where the Class can instantiate only one object, which is globally available. &lt;br /&gt;
&lt;br /&gt;
'''''Need better definition.'''''&lt;br /&gt;
&lt;br /&gt;
Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Example&lt;br /&gt;
     include Singleton&lt;br /&gt;
     ...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
It could be noticed that one must 'require' a module called 'singleton' and include the module within the class.&lt;br /&gt;
This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,&lt;br /&gt;
&lt;br /&gt;
  raisesError = Example.new&lt;br /&gt;
  ruby-1.9.2-p290 :026 &amp;gt; raisesError = Example.new&lt;br /&gt;
  NoMethodError: private method `new' called for Example:Class&lt;br /&gt;
&lt;br /&gt;
We will soon find out we are greeted with the NoMethodError( Some kind of an error is expected ). So how do we use a singleton pattern? We create an instance of it using the keyword 'instance'&lt;br /&gt;
 &lt;br /&gt;
''''''What is meant by Some kind of error is expected? Content here is good, will need to rephrase.''''''&lt;br /&gt;
&lt;br /&gt;
 a = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt; &lt;br /&gt;
 b = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above illustrates how to create the instance of the Singleton class. It also illustrates another point. Even though two 'instances' have supposedly been created, both of them happen to contain reference to the same object. &lt;br /&gt;
This further proves that only one object can be created for a Singleton.&amp;lt;BR&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''''Rephrase again. Not formal enough'''''&lt;br /&gt;
&lt;br /&gt;
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialised&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;.instance&amp;quot; method is defined. One more thing to notice is that, &amp;quot;new&amp;quot; method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.&lt;br /&gt;
&lt;br /&gt;
 Single_ton.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something&lt;br /&gt;
 This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that our class 'behaves' like a singleton. We have a '.instance' method defined and it works.&lt;br /&gt;
The method could be accessed by accessing the lone object inside the class.&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern is useful in situations where serialization is desirable, example logging, communication and database access etc. In these cases, only a single instance of the class is created which accesses and modifies the methods of the class. This ensures safety and also make the single instance responsible for the class.&amp;lt;br&amp;gt;&lt;br /&gt;
[http://c2.com/cgi/wiki?SingletonPattern Here ] is more to read on Singleton patterns.&lt;br /&gt;
&lt;br /&gt;
'''''Feel like there's some flab in the Singleton section that we can cut. Also could think of adding subsections for Default Implemenation, Custom Implementation, Uses etc.'''''&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern, enables classes with incompatible interfaces to work together, by providing the users with a compatible interface.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Lets look at a simple example.&amp;lt;ref&amp;gt;Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We have a class ''Encrypter'' which is used to encrypt files. The ''encrypt'' method takes two open files as arguments. One is a reader which is the input file and other is the writer which is the output file where the encrypted data is stored. It uses a simple encryption algorithm to encrypt each character with a user-specified key.&lt;br /&gt;
&lt;br /&gt;
 class Encrypter&lt;br /&gt;
   def initialize(key)&lt;br /&gt;
     @key = key &lt;br /&gt;
   end&lt;br /&gt;
   def encrypt(reader, writer)&lt;br /&gt;
     key_index = 0&lt;br /&gt;
     while not reader.eof?&lt;br /&gt;
       clear_char = reader.getc&lt;br /&gt;
       encrypted_char = clear_char ^ @key[key_index]&lt;br /&gt;
       writer.putc(encrypted_char)&lt;br /&gt;
       key_index = (key_index + 1) % @key.size&lt;br /&gt;
     end &lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now suppose we want to encrypt a string instead of a file. To be able to use the same ''Encrypter'' class we require an object that looks like an open file - exposes the same methods as the Ruby IO object - on the outside, but actually fetches the data from a string on the inside.&lt;br /&gt;
&lt;br /&gt;
So, we will define a ''StringIOAdapter'' class:&lt;br /&gt;
&lt;br /&gt;
 class StringIOAdapter&lt;br /&gt;
   def initialize(string)&lt;br /&gt;
     @string = string&lt;br /&gt;
     @position = 0&lt;br /&gt;
   end&lt;br /&gt;
   def getc&lt;br /&gt;
     if @position &amp;gt;= @string.length&lt;br /&gt;
       raise EOFError&lt;br /&gt;
     end&lt;br /&gt;
     ch = @string[@position]&lt;br /&gt;
     @position += 1&lt;br /&gt;
     return ch&lt;br /&gt;
   end&lt;br /&gt;
   def eof?&lt;br /&gt;
     return @position &amp;gt;= @string.length&lt;br /&gt;
   end &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
The ''StringIOAdapter'' has two instance variables: a reference to the string to be encrypted and a position index. Each time the function getc is called, the ''StringIOAdapter'' will return the character at current position and increment the position index. If no more characters are left in the string an ''EOFError'' will be raised. The function ''eof?'' will return ''true'' if the string has run out of characters but otherwise will return ''false''.&lt;br /&gt;
&lt;br /&gt;
To use ''Encrypter'' with ''StringIOAdapter'', the ''reader'' input object is defined to be of type ''StringIOAdapter''.&lt;br /&gt;
&lt;br /&gt;
 encrypter = Encrypter.new('OOLS')&lt;br /&gt;
 reader= StringIOAdapter.new('TA position open with Prof. XYZ')&lt;br /&gt;
 writer=File.open('out.txt', 'w')&lt;br /&gt;
 encrypter.encrypt(reader, writer)&lt;br /&gt;
&lt;br /&gt;
Thus the Adapter bridges the chasm between the interface you have and the interface you need.&lt;br /&gt;
&lt;br /&gt;
The class diagram of Adapter class is usually given as:&lt;br /&gt;
&lt;br /&gt;
[[File:Class Diagram - Adapter.png]]&lt;br /&gt;
&lt;br /&gt;
The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. What if we need a more finer to do it.For example, Sometimes one might need to store bunch of code to be used by a peer or himself at a later point. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Patterns] lends itself to our use at this point. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage. And of course, this is implemented with the use of procs in Ruby.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
This is how command pattern is usually implemented. We have a class which holds the commands as a [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object]. And whenever it is to be called, 'call' is used to execute that proc.&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
   def initialize(input)&lt;br /&gt;
     @local_proc = input &lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   def return_proc&lt;br /&gt;
    @local_proc&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we have a class that stores a command. Now let us create a 'command'. &lt;br /&gt;
&lt;br /&gt;
 myProc = proc{ puts 8 }&lt;br /&gt;
&lt;br /&gt;
Now we have a proc object that we want to use.&lt;br /&gt;
&lt;br /&gt;
 obj = Command.new(myProc)&lt;br /&gt;
 obj.return_proc.call&lt;br /&gt;
 8&lt;br /&gt;
&lt;br /&gt;
Then we create an object storing myProc inside it. Then we use the object to return the proc and use 'call' on it to execute it. One could also create an array of commands by simply creating an array of Command objects and storing the proc in them. &amp;lt;br&amp;gt; &lt;br /&gt;
&lt;br /&gt;
One important use of the Command Pattern is to enable the client undo what he has already done, or redo what has been undone by the user. This is done by maintaining a history of the commands executed. As and when the user makes changes, the system creates command after command, executing each command immediately to effect the change. Every undo - able command holds two methods - the execute and the unexecute method.&lt;br /&gt;
The commands are stored in a list and when the user decides to undo a change, the last command on the list is executed to undo the change. The changes can be undone, by going back the history of commands. The redo is done in the similar way where the the commands are re-executed beginning from the last change that what undone to reapply the changes undone. A simple example of the undo - redo use of a Command Pattern is a Calculator with many undo - redo options.&lt;br /&gt;
&lt;br /&gt;
'''''This is not much use without a code example'''''&lt;br /&gt;
&lt;br /&gt;
==Algorithm Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com 1. Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming 2. Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
[http://c2c.com 3. More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://designpatternsinruby.com/section01/article.html 1. Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf 2. Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern 3. Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Adapter_pattern 4. Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Command_pattern 5. Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Strategy_pattern 6. Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Closure_(computer_science) 7. Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
[http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf 8. Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 9. Command and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx 9. Command Pattern]&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_Diagram_-_Adapter.png&amp;diff=66437</id>
		<title>File:Class Diagram - Adapter.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_Diagram_-_Adapter.png&amp;diff=66437"/>
		<updated>2012-10-03T09:08:03Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Adapter Class Diagram: The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adapt&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Adapter Class Diagram: The client expects the target to have some interface. But the target is actually an implementation of the Adapter. The Adapter defines a compatible interface while at the same time there is a reference to a second object - the Adaptee - buried inside it. The Adaptee actually performs the work.&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66144</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w42 js</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w42_js&amp;diff=66144"/>
		<updated>2012-10-02T08:19:53Z</updated>

		<summary type="html">&lt;p&gt;Sanarsal: Added comments for reference&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Design Patterns in Ruby=&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice&amp;quot;'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design&amp;quot;.''&lt;br /&gt;
&lt;br /&gt;
A [http://en.wikipedia.org/wiki/Design_Patterns Design Pattern] is a template to solve a problem which can be used in many different situations. It names, abstracts and identifies the key aspects of a common design structure that makes it useful for creating a reusable object - oriented design. Design Patterns in [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Languages] help show the relationship between the different classes and objects in the program. Design Patterns are tools for building software.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
A [http://www.oodesign.com/ Design Pattern] describes a problem which repeatedly occurs in our environment and also the core of the solution to that problem, in a way that this solution can be re-used many times, without ever doing it the same way twice.&lt;br /&gt;
&lt;br /&gt;
'''''This definition seems a little boring and its too long. Might want to find a better one'''''&lt;br /&gt;
&lt;br /&gt;
The description of a pattern consists of:&lt;br /&gt;
* '''''The Pattern name''''', describes the design pattern, its solutions and consequences.&lt;br /&gt;
* '''''The problem the pattern solves''''', describes when to apply the pattern.&lt;br /&gt;
* '''''The solution''''', describes the elements that make up the design, their relationships, responsibilities, and collaborations.&lt;br /&gt;
* '''''The consequences''''', describes the results of applying the pattern to the problem.&lt;br /&gt;
&lt;br /&gt;
'''''This does not make much sense to be written here. None of the descriptions for design patterns below use these four points.'''''&lt;br /&gt;
&lt;br /&gt;
The different types of design patterns can be categorized and listed as below:&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Creational_pattern Creational Pattern], which help create the objects for the user, instead of having the user to instantiate the object.&lt;br /&gt;
* '''''Singleton Design Pattern''''', which is used to have only one instance of a class. &lt;br /&gt;
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.&lt;br /&gt;
* '''''Adapter Design Pattern''''', which enables classes with incompatible interfaces to work together.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.&lt;br /&gt;
* '''''Command Design Pattern''''', which enables to pass around the code that needs to be executed later.&lt;br /&gt;
* '''''Algorithm Strategy Pattern''''', which helps choose an algorithm to fulfill a task based on some &amp;quot;parameter&amp;quot; of the situation.&lt;br /&gt;
&lt;br /&gt;
'''''There are lot of patterns in each of the categories. There's no mention of them. If the idea is that we these are the patterns available out of the box in ruby, it should be explicitly mentioned here.'''''&lt;br /&gt;
&lt;br /&gt;
=Creational Pattern=&lt;br /&gt;
==Singleton Pattern==&lt;br /&gt;
The first design pattern one should know about is the [http://www.oodesign.com/singleton-pattern.html Singleton patterns]. It is basically the case, where the Class can instantiate only one object, which is globally available. &lt;br /&gt;
&lt;br /&gt;
'''''Need better definition.'''''&lt;br /&gt;
&lt;br /&gt;
Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:&lt;br /&gt;
&lt;br /&gt;
 require 'singleton'&lt;br /&gt;
 class Example&lt;br /&gt;
     include Singleton&lt;br /&gt;
     ...&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
It could be noticed that one must 'require' a module called 'singleton' and include the module within the class.&lt;br /&gt;
This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,&lt;br /&gt;
&lt;br /&gt;
  raisesError = Example.new&lt;br /&gt;
  ruby-1.9.2-p290 :026 &amp;gt; raisesError = Example.new&lt;br /&gt;
  NoMethodError: private method `new' called for Example:Class&lt;br /&gt;
&lt;br /&gt;
We will soon find out we are greeted with the NoMethodError( Some kind of an error is expected ). So how do we use a singleton pattern? We create an instance of it using the keyword 'instance'&lt;br /&gt;
 &lt;br /&gt;
''''''What is meant by Some kind of error is expected? Content here is good, will need to rephrase.''''''&lt;br /&gt;
&lt;br /&gt;
 a = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt; &lt;br /&gt;
 b = Example.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Example:0x9361cb8&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above illustrates how to create the instance of the Singleton class. It also illustrates another point. Even though two 'instances' have supposedly been created, both of them happen to contain reference to the same object. &lt;br /&gt;
This further proves that only one object can be created for a Singleton.&amp;lt;BR&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''''Rephrase again. Not formal enough'''''&lt;br /&gt;
&lt;br /&gt;
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.&lt;br /&gt;
&lt;br /&gt;
 class Single_ton&lt;br /&gt;
 def initialize&lt;br /&gt;
    puts &amp;quot;Initialised&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
 @@instance = Single_ton.new&lt;br /&gt;
  &lt;br /&gt;
 def self.instance&lt;br /&gt;
    return @@instance&lt;br /&gt;
 end&lt;br /&gt;
  &lt;br /&gt;
 def print_something&lt;br /&gt;
   puts &amp;quot;This prints something&amp;quot;&lt;br /&gt;
 end&lt;br /&gt;
   &lt;br /&gt;
 private_class_method :new&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
The above snippet is actually a singleton class. A cursory reading shall read the logic behind singleton-ing the class. An object to the same class has been created as a class variable. a &amp;quot;.instance&amp;quot; method is defined. One more thing to notice is that, &amp;quot;new&amp;quot; method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.&lt;br /&gt;
&lt;br /&gt;
 Single_ton.instance&lt;br /&gt;
 =&amp;gt; #&amp;lt;Single_ton:0x94483d4&amp;gt; &lt;br /&gt;
 Single_ton.instance.print_something&lt;br /&gt;
 This prints something&lt;br /&gt;
&lt;br /&gt;
The above snippet shows that our class 'behaves' like a singleton. We have a '.instance' method defined and it works.&lt;br /&gt;
The method could be accessed by accessing the lone object inside the class.&lt;br /&gt;
&lt;br /&gt;
The Singleton Pattern is useful in situations where serialization is desirable, example logging, communication and database access etc. In these cases, only a single instance of the class is created which accesses and modifies the methods of the class. This ensures safety and also make the single instance responsible for the class.&amp;lt;br&amp;gt;&lt;br /&gt;
[http://c2.com/cgi/wiki?SingletonPattern Here ] is more to read on Singleton patterns.&lt;br /&gt;
&lt;br /&gt;
'''''Feel like there's some flab in the Singleton section that we can cut. Also could think of adding subsections for Default Implemenation, Custom Implementation, Uses etc.'''''&lt;br /&gt;
&lt;br /&gt;
=Structural Patterns=&lt;br /&gt;
==Adapter Pattern==&lt;br /&gt;
&lt;br /&gt;
An [http://www.oodesign.com/adapter-pattern.html Adapter pattern], also known as the Wrapper Pattern enables classes with incompatible interfaces to work together, by providing the users with its interface. This is achieved by:&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
In other words, when we want our new class to support a pre-existing feature, instead of modifying our new class, we can 'wrap' a similar feature in our new class to behave like the older class so that the pre-existing feature is supported.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''''Some cleaning up to do'''''&lt;br /&gt;
&lt;br /&gt;
Consider a software company located in United Kingdom. Lets assume they have these classes in their system.&lt;br /&gt;
&lt;br /&gt;
 class Bicycle&lt;br /&gt;
   def rideBiCycle&lt;br /&gt;
     puts 'Iam riding a bicycle'&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
 &lt;br /&gt;
The following class has a method which calls the method 'rideBiCycle' in the passed argument. &lt;br /&gt;
 &lt;br /&gt;
 class Tester&lt;br /&gt;
   def displayRide(object)&lt;br /&gt;
     object.rideBiCycle&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
Now, If an American company buys this British company and tries to reuse the code. It has the following class already to its use.&lt;br /&gt;
&lt;br /&gt;
 class Bike&lt;br /&gt;
   def rideBike&lt;br /&gt;
     puts 'I am riding a bike'&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
But, the problem is that, Bike doesn't have the function 'rideBiCycle', so it cannot use the Tester class directly. If that tester class sits in a very important part of the code, there is a problem. Now the way out is to create a 'adapter' which assimilates a 'bike' object. This adapter is actually a 'Bike' which can mimic itself like a 'Bicycle' by supporting the method 'rideBiCycle'.&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
Now to understand it. We will create a bunch of instances.&lt;br /&gt;
&lt;br /&gt;
 cycle = Bicycle.new&lt;br /&gt;
 cycle.rideBiCycle&lt;br /&gt;
 Iam riding a bicycle&lt;br /&gt;
&lt;br /&gt;
 test = Tester.new&lt;br /&gt;
 test.displayRide(cycle)&lt;br /&gt;
&lt;br /&gt;
 bike = Bike.new&lt;br /&gt;
 bike.rideBike&lt;br /&gt;
 I am riding a bike &lt;br /&gt;
&lt;br /&gt;
So far, the respective objects are working well when used in isolation. But when we have to do this,&lt;br /&gt;
&lt;br /&gt;
  test.displayRide(bike)&lt;br /&gt;
  NoMethodError: undefined method `rideBiCycle' for #&amp;lt;Bike:0x94b4494&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We encounter an error which is pretty obvious because rideBiCycle is not defined in Bike. Now let us define the adapter,&lt;br /&gt;
 &lt;br /&gt;
 class BikeAdapter&lt;br /&gt;
   def initialize(bike)&lt;br /&gt;
     @bikeObject = bike&lt;br /&gt;
     end&lt;br /&gt;
   def rideBiCycle&lt;br /&gt;
     @bikeObject.rideBike&lt;br /&gt;
   end                                                                                                                 &lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we can try the failed method call like this,&lt;br /&gt;
&lt;br /&gt;
 adapter = BikeAdapter.new(bike)&lt;br /&gt;
 test.displayRide(adapter)&lt;br /&gt;
 Iam riding a bike&lt;br /&gt;
&lt;br /&gt;
Voila! We have succesfully 'adapted' Bike class to behave like 'Bicycle'.&amp;lt;br&amp;gt;&lt;br /&gt;
[http://c2.com/cgi/wiki?AdapterPattern This one ] is a good read on Adapter patterns and also contains links to other articles about Adapter Pattern.&lt;br /&gt;
&lt;br /&gt;
'''''I found the example thoroughly confusing. Let me know what you think.'''''&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
==Closures and Patterns==&lt;br /&gt;
&lt;br /&gt;
Patterns can be implemented using Closures. A [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2011/ch3_3a_av#Closures Closure] can be described as a block of code ith the properties mentioned below:&lt;br /&gt;
&lt;br /&gt;
* The block of code can be passed around like a value.&lt;br /&gt;
* Any procedure or method that has the value can execute it.&lt;br /&gt;
* A Closure can refer to the variables from the context in which it was created. &lt;br /&gt;
&lt;br /&gt;
'''''Why does he/she start off with Closures and Patterns? Since there's a whole section on it elsewhere, makes no sense to give such a hasty explanation that doesn't make stuff clear at all. What is meant by Patterns can be implemented using closures? Can all patterns be implemented using closures?'''''&lt;br /&gt;
&lt;br /&gt;
The Command Design Pattern and Strategy Design Patterns are examples of this.&lt;br /&gt;
&lt;br /&gt;
==Command Pattern==&lt;br /&gt;
&lt;br /&gt;
The design patterns we saw above deal with classes and work around the way classes and objects are manipulated, interpreted, created etc. Actually, the adapter pattern bases its necessity on the need for 'code reuse'. But, it can only implement code reuse at a class or method level. What if we need a more finer to do it.For example, Sometimes one might need to store bunch of code to be used by a peer or himself at a later point. This bunch of code is not associated with any class, or any method. &lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com/command-pattern.html Command Patterns] lends itself to our use at this point. With command pattern it is possible to store a piece of code or a set of commands to be executed at a later stage. And of course, this is implemented with the use of procs in Ruby.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
This is how command pattern is usually implemented. We have a class which holds the commands as a [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Object]. And whenever it is to be called, 'call' is used to execute that proc.&lt;br /&gt;
&lt;br /&gt;
 class Command&lt;br /&gt;
   def initialize(input)&lt;br /&gt;
     @local_proc = input &lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   def return_proc&lt;br /&gt;
    @local_proc&lt;br /&gt;
   end&lt;br /&gt;
 end&lt;br /&gt;
&lt;br /&gt;
Now we have a class that stores a command. Now let us create a 'command'. &lt;br /&gt;
&lt;br /&gt;
 myProc = proc{ puts 8 }&lt;br /&gt;
&lt;br /&gt;
Now we have a proc object that we want to use.&lt;br /&gt;
&lt;br /&gt;
 obj = Command.new(myProc)&lt;br /&gt;
 obj.return_proc.call&lt;br /&gt;
 8&lt;br /&gt;
&lt;br /&gt;
Then we create an object storing myProc inside it. Then we use the object to return the proc and use 'call' on it to execute it. One could also create an array of commands by simply creating an array of Command objects and storing the proc in them. &amp;lt;br&amp;gt; &lt;br /&gt;
&lt;br /&gt;
One important use of the Command Pattern is to enable the client undo what he has already done, or redo what has been undone by the user. This is done by maintaining a history of the commands executed. As and when the user makes changes, the system creates command after command, executing each command immediately to effect the change. Every undo - able command holds two methods - the execute and the unexecute method.&lt;br /&gt;
The commands are stored in a list and when the user decides to undo a change, the last command on the list is executed to undo the change. The changes can be undone, by going back the history of commands. The redo is done in the similar way where the the commands are re-executed beginning from the last change that what undone to reapply the changes undone. A simple example of the undo - redo use of a Command Pattern is a Calculator with many undo - redo options.&lt;br /&gt;
&lt;br /&gt;
'''''This is not much use without a code example'''''&lt;br /&gt;
&lt;br /&gt;
==Algorithm Strategy Pattern==&lt;br /&gt;
&lt;br /&gt;
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some &amp;quot;parameters&amp;quot; of the situation. Also known as the Policy Pattern, it enables selection of algorithms at runtime. This pattern allows the algorithm to vary irresepctive of the user that uses it.&lt;br /&gt;
&lt;br /&gt;
The strategy pattern ''&amp;quot;defines a family of algorithms, encapsulates each one, and makes them interchangeable&amp;quot;''.&lt;br /&gt;
&lt;br /&gt;
Consider as an example, a class that that converts among different types of file formats like jpeg, jif, png etc. We can write a case statement to choose what algorithm has to be employed for each type of format. Another example could be performing validation on incoming data. Here we can select a validation algorithm based on the type and source of data.  &lt;br /&gt;
&lt;br /&gt;
A Strategy Pattern is best implemented using [http://www.ruby-doc.org/core-1.9.2/Proc.html Proc Objects]. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:&lt;br /&gt;
&lt;br /&gt;
 class findArea&lt;br /&gt;
     attr_accessor :strategy&lt;br /&gt;
     def calArea(x,y)&lt;br /&gt;
          strategy.call(*args)&lt;br /&gt;
     end&lt;br /&gt;
     def area_square … end&lt;br /&gt;
     def area_rect … end&lt;br /&gt;
 end&lt;br /&gt;
 &lt;br /&gt;
Here, we have a class findArea, which calculates the area of the given geometric shape by invoking the methods area_square or area_rect based upon whether the given figure is a square or rectangle.&lt;br /&gt;
&lt;br /&gt;
 sides = findArea.new&lt;br /&gt;
 if x == y&lt;br /&gt;
       puts &amp;quot;The given object is a square&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_square)&lt;br /&gt;
 else&lt;br /&gt;
       puts &amp;quot;The given object is a rectangle&amp;quot;&lt;br /&gt;
       sides.strategy = findArea.method(:area_rect)&lt;br /&gt;
 end&lt;br /&gt;
 sides.calArea(x,y)&lt;br /&gt;
&lt;br /&gt;
Here, the path or strategy chosen is based on an if condition involving the values of x and y which are not known until runtime. Therefore, the algorithm that will be made use of to calculate the area, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.&lt;br /&gt;
&lt;br /&gt;
=Differences between Command and Strategy Pattern=&lt;br /&gt;
&lt;br /&gt;
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it. &lt;br /&gt;
* A Strategy Pattern, enables us to customize an algorithm, deciding which algorithm has to be made use of depending on a number of dynamically changing factors. A given strategy has many methods associated with it.&lt;br /&gt;
&lt;br /&gt;
=Comparsion of the different Design Patterns=&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot; style=&amp;quot;font-size: 90%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! Comparison Factor&lt;br /&gt;
! Singleton Pattern&lt;br /&gt;
! Adapter Pattern&lt;br /&gt;
! Command Pattern&lt;br /&gt;
! Strategy Pattern&lt;br /&gt;
|-&lt;br /&gt;
! Intent&lt;br /&gt;
! Ensure only one object of a class is instantiated, provide a global point of access to that object&lt;br /&gt;
! Convert the interface of a class into one that the client expects &lt;br /&gt;
! Encapsulate a request in an object and allow the parameterization of clients with different requests&lt;br /&gt;
! Encapsulate a set of algorithms and use them interchangeably.&lt;br /&gt;
|- &lt;br /&gt;
! Advantages&lt;br /&gt;
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations&lt;br /&gt;
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.&lt;br /&gt;
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.&lt;br /&gt;
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.&lt;br /&gt;
|- &lt;br /&gt;
! Disadvantages&lt;br /&gt;
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.&lt;br /&gt;
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. &lt;br /&gt;
! The increase in the number of Command Classes, clutters up the design. &lt;br /&gt;
! The increase in the number of objects, and all the algorithms use the same interface.&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
'''''We could also add a section on drawbacks of design patterns. I found a link on that.'''''&lt;br /&gt;
=See Also=&lt;br /&gt;
&lt;br /&gt;
[http://www.oodesign.com 1. Object Oriented Design]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-oriented_programming 2. Object - Oriented Programming]&lt;br /&gt;
&lt;br /&gt;
[http://c2c.com 3. More Object oriented Programming]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
[http://designpatternsinruby.com/section01/article.html 1. Article on Design Patterns in Ruby]&lt;br /&gt;
&lt;br /&gt;
[http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf 2. Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma] &lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Singleton_pattern 3. Wiki - Singleton Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Adapter_pattern 4. Wiki - Adapter Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Command_pattern 5. Wiki - Command Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Strategy_pattern 6. Wiki - Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Closure_(computer_science) 7. Wiki - Closures]&lt;br /&gt;
&lt;br /&gt;
[http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf 8. Lec 13 - Class Notes]&lt;br /&gt;
&lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 9. Command and Strategy Pattern]&lt;br /&gt;
&lt;br /&gt;
[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx 9. Command Pattern]&lt;/div&gt;</summary>
		<author><name>Sanarsal</name></author>
	</entry>
</feed>