CSC/ECE 517 Fall 2011/ch4 4h sv: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(76 intermediate revisions by 2 users not shown)
Line 1: Line 1:
=Design Patterns in Ruby=
=Design Patterns in Ruby=


''"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"'' - Christopher Alexander
''"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"'' - [http://www.patternlanguage.com/leveltwo/ca.htm Christopher Alexander]


''"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design".''
''"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design".''


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.
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.


__TOC__
__TOC__
Line 11: Line 11:
==Overview==
==Overview==


A 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.
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.


The description of a pattern involves:
The description of a pattern consists of:
* The name of the pattern.
* '''''The Pattern name''''', describes the design pattern, its solutions and consequences.
* The problem the pattern solves.
* '''''The problem the pattern solves''''', describes when to apply the pattern.
* How the pattern can be implemented.
* '''''The solution''''', describes the elements that make up the design, their relationships, responsibilities, and collaborations.
* The constraints we have to consider in order to implement it.
* '''''The consequences''''', describes the results of applying the pattern to the problem.


There are different types of design patterns:
The different types of design patterns can be categorized and listed as below:


[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.
* '''''Singleton Design Pattern''''', which is used to have only one instance of a class.  
* '''''Singleton Design Pattern''''', which is used to have only one instance of a class.  
[http://en.wikipedia.org/wiki/Structural_pattern Structural Pattern], which employ interfaces to achieve inheritance to enable objects to obtain new functionality.
* '''''Adapter Design Pattern''''', which enables classes with incompatible interfaces to work together.
* '''''Adapter Design Pattern''''', which enables classes with incompatible interfaces to work together.
[http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral Pattern], which are concerned with communication between objects.
* '''''Command Design Pattern''''', which enables to pass around the code that needs to be executed later.
* '''''Command Design Pattern''''', which enables to pass around the code that needs to be executed later.
* '''''Algorithm Strategy Pattern''''', which helps choose an algorithm to fulfill a task based on some "parameter" of the situation.
* '''''Algorithm Strategy Pattern''''', which helps choose an algorithm to fulfill a task based on some "parameter" of the situation.


==Singleton Pattern==
==Singleton Pattern==
The Singleton design pattern is used to restrict the instantiation of a class to only one instance which is globally available. This is used in situations where a user needs an instance of the class to be available in various parts of the application, being available for logging functionality, communictaion with external systems and database access etc. 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.
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.  


Below is an illustration of the implementation of Singleton Design Pattern in Ruby:
Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:


  require 'singleton'
  require 'singleton'
  class Example
  class Example
    attr_accessor :val
     include Singleton
     include Singleton
    ...
  end
  end
   
   
In the above declaration of a class, including the Singleton module makes the class's new method private. To create an object of that class, the users call the instance method, which returns a singleton instance of the class.
It could be noticed that one must 'require' a module called 'singleton' and include the module within the class.
This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,
 
  raisesError = Example.new
  ruby-1.9.2-p290 :026 > raisesError = Example.new
  NoMethodError: private method `new' called for Example:Class
 
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'
   
   
  a = Example.instance
  a = Example.instance
=> #<Example:0x9361cb8>
  b = Example.instance
  b = Example.instance
=> #<Example:0x9361cb8>
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.
This further proves that only one object can be created for a Singleton.<BR>
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.
class Single_ton
def initialize
    puts "Initialised"
end
@@instance = Single_ton.new
 
def self.instance
    return @@instance
end
 
def print_something
  puts "This prints something"
end
 
private_class_method :new
end
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 ".instance" method is defined. One more thing to notice is that, "new" method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.
Single_ton.instance
=> #<Single_ton:0x94483d4>
Single_ton.instance.print_something
This prints something


Here, the instances a and b of the class Example are essentially the same object. When a value of 007 is assigned to a, the value of b is also the same.
The above just shows that our class 'behaves' like a singleton. we have a '.instance' method defind and it works.
The method could be accessed by accessing the lone object inside the class.


a.val = 007
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.<br>
puts b.val
[http://c2.com/cgi/wiki?SingletonPattern Here ] is more to read on Singleton patterns.
=> 007


The Singleton Pattern is useful in situations where serialization is desirable, like 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.
==Adapter Pattern==


Below is an illustration of the Singleton Design Pattern without using the Singleton library. Here, we can observe that the class Logger's new method has been explicitly declared to be private.
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:
<br>
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.
<br>
Consider a software company located in United Kingdom. Lets assume they have these classes in their system.


  class Logger
  class Bicycle
  def initialize
  def rideBiCycle
    @log = File.open("log.txt", "a")
    puts 'Iam riding a bicycle'
  end
    end
    
   end
  @@instance = Logger.new
   
   
  def self.instance
The following class has a method which calls the method 'rideBiCycle' in the passed argument.  
    return @@instance
  end
   
   
  def log(msg)
class Tester
    @log.puts(msg)
  def displayRide(object)
    object.rideBiCycle
    end
  end
 
Now, If an American company buys this British company and tries to reuse the code. It has the following class already to its use.
 
class Bike
  def rideBike
    puts 'I am riding a bike'
    end
   end
   end
  private_class_method :new
end
Logger.instance.log('message 1')


In this code example, inside class Logger we create instance of the very same class Logger and we can access that instance with class method Logger.instance whenever we need to write something to the log file using the instance method "log". In the initialize method we just opened a log file for appending, and at the end of Logger class, we made method "new" private so that we cannot create new instances of class Logger. And, that is Singleton Pattern: only one instance, globally available.
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'.
<br>
Now to understand it. We will create a bunch of instances.
 
cycle = Bicycle.new
cycle.rideBiCycle
Iam riding a bicycle


==Adapter Pattern==
test = Tester.new
test.displayRide(cycle)


An [http://en.wikipedia.org/wiki/Adapter_pattern Adapter Design 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:
bike = Bike.new
bike.rideBike
I am riding a bike


* “Wrapping” its own interface around the interface of a pre-existing class.  
So far, the respective objects are working well when used in isolation. But when we have to do this,
* Besides, it may also translate data formats from the caller to a form needed by the callee. Example: If the caller stores boolean value in terms of integers but the callee needs the values as 'true/false', the adapter pattern would extract the right value from the caller and pass it on to the callee. This ensures that the caller and callee can work together.


The purpose of an adapter is “to convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”
  test.displayRide(bike)
  NoMethodError: undefined method `rideBiCycle' for #<Bike:0x94b4494>


Below is an illustration of the Adapter Pattern:
We encounter an error which is pretty obvious because rideBiCycle is not defined in Bike. Now let us define the adapter,
class BikeAdapter
  def initialize(bike)
    @bikeObject = bike
    end
  def rideBiCycle
    @bikeObject.rideBike
  end                                                                                                               
end


Now we can try the failed method call like this,


===Types of Adapter Patterns===
adapter = BikeAdapter.new(bike)
test.displayRide(adapter)
Iam riding a bike


Based on the structure, there are two types of Adapter Patterns:
Voila! We have succesfully 'adapted' Bike class to behave like 'Bicycle'.<br>
[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.


====Object Adapter Pattern====
==Closures and Patterns==


The Adapter Pattern has an instance of the classit "wraps" and makes calls to this wrapped object alone.
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:


====Class Adapter Pattern====
* The block of code can be passed around like a value.
* Any procedure or method that has the value can execute it.
* A Closure can refer to the variables from the context in which it was created.


Polymorphic Interfaces are used by this type of pattern, where the interface that is expected and the interface that is available are both inherited or implemented. This is used in situations where the class providing the services you need does not provide the interface required.
The Command Design Pattern and Strategy Design Patterns are examples of this.


==Command Pattern==
==Command Pattern==


At times, it is needed to pass around code that needs to be executed later. This is achieved by employing the Command Design Pattern which is used to factor out the action code of a class into its own object. The Command Pattern is implemented using Closures. A Command class holds an object, method along with the information needed to call a method at a later time. This information includes the method name with the values for the method parameters. The 'Call' method of Ruby brings the different parts together when needed.
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.  
<br>


This is illustrated using the following example:
[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.


One example is a check at a restaurant.
<br>
* The waiter/waitress takes an order from a customer and writes it on a check.
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.
* The check is then queued for the cook, who prepares the food as requested by the customer.
 
* The check is later returned to the server, who uses it to bill the customer.
class Command
  def initialize(input)
    @local_proc = input
  end
 
  def return_proc
    @local_proc
  end
end


In this example, the check has nothing to do with the menu. In principle, the same checks could be used at any restaurant.
Now we have a class that stores a command. Now let us create a 'command'.  


The command pattern is made up of a client, invoker and receiver. A client creates an object of the Command class and provides the information required to call the method at a later time. The invoker decides when the method should be called. The receiver is the class object which contains the code of the method. The usage of command objects makes it easier to construct components which need to execute methods at a later time without having knowledge about the method's owner or parameters.
myProc = proc{ puts 8 }


This Pattern can be implemented using the Proc objects, which is a callable block of code that closes over the variables in scope when it was created. This gives us a concise implementation of Command Pattern.
Now we have a proc object that we want to use.


Below is an illustration of the Command Design Pattern, using Proc Objects:
obj = Command.new(myProc)
obj.return_proc.call
8


count = 0
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. <br>
commands = []
(1..10).each do |i|
commands << proc { count += i }
end
puts "Count is initially #{count}"
commands.each { |cmd| cmd.call }
puts "Performed all commands. count is #{count}"


Another 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.
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.
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.
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.


==Algorithm Strategy Pattern==
==Algorithm Strategy Pattern==


The Strategy Pattern helps choose an algorithm to accomplish a task based on some "parameters" of the situaton. 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.
The [http://www.oodesign.com/strategy-pattern.html Strategy Pattern] helps choose an algorithm to accomplish a task based on some "parameters" 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.


The strategy pattern ''"defines a family of algorithms, encapsulates each one, and makes them interchangeable"''.
The strategy pattern ''"defines a family of algorithms, encapsulates each one, and makes them interchangeable"''.
Line 137: Line 214:
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.   
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.   


A Strategy Pattern is best implemented using Proc Objects. Below is an illustration of it:
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:


  class RoutePlanner
  class findArea
     attr_accessor :strategy
     attr_accessor :strategy
     def go(pointA, pointB)
     def calArea(x,y)
           strategy.call(*args)
           strategy.call(*args)
     end
     end
     def fastest … end
     def area_square … end
     def shortest … end
     def area_rect … end
  end
  end
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.


Here, we have a class which helps us plan the route between two points A and B, depending upon whether we want the shortest path or the fastest path.
sides = findArea.new
if x == y
      puts "The given object is a square"
      sides.strategy = findArea.method(:area_square)
else
      puts "The given object is a rectangle"
      sides.strategy = findArea.method(:area_rect)
end
sides.calArea(x,y)


ctx = RoutePlanner.new
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.
if on_foot
    ctx.strategy = RoutePlanner.method(:shortest)
else
    ctx.strategy = RoutePlanner.method(:fastest)
ctx.go(pointA, pointB)
 
Here, the path or strategy chosen is based on an if condition involving the value of the variable on_foot which is not known until runtime. Therefore, the algorithm that will be made use of to reach B starting from A, is decided at run time. The strategy that will be chosen depends on many factors which change dynamically.  


==Differences between Command and Strategy Pattern==
==Differences between Command and Strategy Pattern==
Line 163: Line 243:
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it.  
* A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it.  
* 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.
* 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.
==Comparsion of the different Design Patterns==
{| class="wikitable sortable" style="font-size: 90%; text-align: center; width: auto;"
|-
! Comparison Factor
! Singleton Pattern
! Adapter Pattern
! Command Pattern
! Strategy Pattern
|-
! Intent
! Ensure only one object of a class is instantiated, provide a global point of access to that object
! Convert the interface of a class into one that the client expects
! Encapsulate a request in an object and allow the parameterization of clients with different requests
! Encapsulate a set of algorithms and use them interchangeably.
|-
! Advantages
! Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations
! Enables classes to communicate which otherwise would not be able to due to incompatible interfaces.
! Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object.
! Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.
|-
! Disadvantages
! Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program.
! When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written.
! The increase in the number of Command Classes, clutters up the design.
! The increase in the number of objects, and all the algorithms use the same interface.
|}
==See Also==
[http://www.oodesign.com 1. Object Oriented Design]
[http://en.wikipedia.org/wiki/Object-oriented_programming 2. Object - Oriented Programming]
[http://c2c.com 3. More Object oriented Programming]


==References==
==References==
http://designpatternsinruby.com/section01/article.html
 
http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf
[http://designpatternsinruby.com/section01/article.html 1. Article on Design Patterns in Ruby]
 
[http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf 2. Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma]
 
[http://en.wikipedia.org/wiki/Singleton_pattern 3. Wiki - Singleton Pattern]
 
[http://en.wikipedia.org/wiki/Adapter_pattern 4. Wiki - Adapter Pattern]
 
[http://en.wikipedia.org/wiki/Command_pattern 5. Wiki - Command Pattern]
 
[http://en.wikipedia.org/wiki/Strategy_pattern 6. Wiki - Strategy Pattern]
 
[http://en.wikipedia.org/wiki/Closure_(computer_science) 7. Wiki - Closures]
 
[http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf 8. Lec 13 - Class Notes]
 
[https://docs.google.com/a/ncsu.edu/viewer?a=v&q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&hl=en&gl=us&pid=bl&srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&pli=1 9. Command and Strategy Pattern]
 
[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx 9. Command Pattern]

Latest revision as of 18:12, 29 October 2011

Design Patterns in Ruby

"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" - Christopher Alexander

"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design".

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.

Overview

A 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.

The description of a pattern consists of:

  • The Pattern name, describes the design pattern, its solutions and consequences.
  • The problem the pattern solves, describes when to apply the pattern.
  • The solution, describes the elements that make up the design, their relationships, responsibilities, and collaborations.
  • The consequences, describes the results of applying the pattern to the problem.

The different types of design patterns can be categorized and listed as below:

Creational Pattern, which help create the objects for the user, instead of having the user to instantiate the object.

  • Singleton Design Pattern, which is used to have only one instance of a class.

Structural Pattern, which employ interfaces to achieve inheritance to enable objects to obtain new functionality.

  • Adapter Design Pattern, which enables classes with incompatible interfaces to work together.

Behavioral Pattern, which are concerned with communication between objects.

  • Command Design Pattern, which enables to pass around the code that needs to be executed later.
  • Algorithm Strategy Pattern, which helps choose an algorithm to fulfill a task based on some "parameter" of the situation.

Singleton Pattern

The first design pattern one should know about is the Singleton patterns. It is basically the case, where the Class can instantiate only one object, which is globally available.

Below is an illustration of the general Syntax of Singleton Design Pattern in Ruby:

require 'singleton'
class Example
    include Singleton
    ...
end

It could be noticed that one must 'require' a module called 'singleton' and include the module within the class. This adds the singleton flavour to your class. Now to test if it can create multiple instances, we can inquisitively try this,

 raisesError = Example.new
 ruby-1.9.2-p290 :026 > raisesError = Example.new
 NoMethodError: private method `new' called for Example:Class

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'

a = Example.instance
=> #<Example:0x9361cb8> 
b = Example.instance
=> #<Example:0x9361cb8>

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. This further proves that only one object can be created for a Singleton.
That was the Ruby's default way to create singletons. Singletons can be created manually without using the 'singleton' module.

class Single_ton
def initialize
   puts "Initialised"
end

@@instance = Single_ton.new
 
def self.instance
   return @@instance
end
 
def print_something
  puts "This prints something"
end
  
private_class_method :new
end

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 ".instance" method is defined. One more thing to notice is that, "new" method is made 'private'. This makes sure that one cannot create anymore objects of the singleton.

Single_ton.instance
=> #<Single_ton:0x94483d4> 
Single_ton.instance.print_something
This prints something

The above just shows that our class 'behaves' like a singleton. we have a '.instance' method defind and it works. The method could be accessed by accessing the lone object inside the class.


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.
Here is more to read on Singleton patterns.

Adapter Pattern

An 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:
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.
Consider a software company located in United Kingdom. Lets assume they have these classes in their system.

class Bicycle
  def rideBiCycle
    puts 'Iam riding a bicycle'
    end
  end

The following class has a method which calls the method 'rideBiCycle' in the passed argument.

class Tester
  def displayRide(object)
    object.rideBiCycle
    end
  end

Now, If an American company buys this British company and tries to reuse the code. It has the following class already to its use.

class Bike
  def rideBike
    puts 'I am riding a bike'
   end
 end

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'.
Now to understand it. We will create a bunch of instances.

cycle = Bicycle.new
cycle.rideBiCycle
Iam riding a bicycle
test = Tester.new
test.displayRide(cycle)
bike = Bike.new
bike.rideBike
I am riding a bike 

So far, the respective objects are working well when used in isolation. But when we have to do this,

 test.displayRide(bike)
 NoMethodError: undefined method `rideBiCycle' for #<Bike:0x94b4494>

We encounter an error which is pretty obvious because rideBiCycle is not defined in Bike. Now let us define the adapter,

class BikeAdapter
  def initialize(bike)
    @bikeObject = bike
    end
  def rideBiCycle
    @bikeObject.rideBike
  end                                                                                                                 
end

Now we can try the failed method call like this,

adapter = BikeAdapter.new(bike)
test.displayRide(adapter)
Iam riding a bike

Voila! We have succesfully 'adapted' Bike class to behave like 'Bicycle'.
This one is a good read on Adapter patterns and also contains links to other articles about Adapter Pattern.

Closures and Patterns

Patterns can be implemented using Closures. A Closure can be described as a block of code ith the properties mentioned below:

  • The block of code can be passed around like a value.
  • Any procedure or method that has the value can execute it.
  • A Closure can refer to the variables from the context in which it was created.

The Command Design Pattern and Strategy Design Patterns are examples of this.

Command Pattern

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.

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.


This is how command pattern is usually implemented. We have a class which holds the commands as a Proc Object. And whenever it is to be called, 'call' is used to execute that proc.

class Command
  def initialize(input)
    @local_proc = input 
  end
  def return_proc
   @local_proc
  end
end

Now we have a class that stores a command. Now let us create a 'command'.

myProc = proc{ puts 8 }

Now we have a proc object that we want to use.

obj = Command.new(myProc)
obj.return_proc.call
8

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.

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. 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.

Algorithm Strategy Pattern

The Strategy Pattern helps choose an algorithm to accomplish a task based on some "parameters" 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.

The strategy pattern "defines a family of algorithms, encapsulates each one, and makes them interchangeable".

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.

A Strategy Pattern is best implemented using Proc Objects. Below is an example of the Strategy Pattern which deals with areas of geometric shapes:

class findArea
    attr_accessor :strategy
    def calArea(x,y)
         strategy.call(*args)
    end
    def area_square … end
    def area_rect … end
end

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.

sides = findArea.new
if x == y
      puts "The given object is a square"
      sides.strategy = findArea.method(:area_square)
else
      puts "The given object is a rectangle"
      sides.strategy = findArea.method(:area_rect)
end
sides.calArea(x,y)

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.

Differences between Command and Strategy Pattern

  • A Command Pattern encapsulates a single action. A command object has a single method with a generic signature associated with it.
  • 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.

Comparsion of the different Design Patterns

Comparison Factor Singleton Pattern Adapter Pattern Command Pattern Strategy Pattern
Intent Ensure only one object of a class is instantiated, provide a global point of access to that object Convert the interface of a class into one that the client expects Encapsulate a request in an object and allow the parameterization of clients with different requests Encapsulate a set of algorithms and use them interchangeably.
Advantages Helps achieve serialization and is useful in scenarios of logging, communication and lazy instantiations Enables classes to communicate which otherwise would not be able to due to incompatible interfaces. Addition of new functionality is fairly simple as it just calls for encapsulating the functionality into the Command Object. Large conditional statements are eliminated which makes it easy to keep track of the different behaviors which are now in separate classes.
Disadvantages Brings in the concept of global state, making unit testing difficult. Also reduces the scope of parallelism within the program. When using Object Adapters, all the code for delegating all the necessary requests to the Adaptee has to be written. The increase in the number of Command Classes, clutters up the design. The increase in the number of objects, and all the algorithms use the same interface.

See Also

1. Object Oriented Design

2. Object - Oriented Programming

3. More Object oriented Programming

References

1. Article on Design Patterns in Ruby

2. Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma

3. Wiki - Singleton Pattern

4. Wiki - Adapter Pattern

5. Wiki - Command Pattern

6. Wiki - Strategy Pattern

7. Wiki - Closures

8. Lec 13 - Class Notes

9. Command and Strategy Pattern

9. Command Pattern