CSC/ECE 517 Fall 2009/wiki2 11 zv

From Expertiza_Wiki
Revision as of 05:20, 7 October 2009 by Crazzyy (talk | contribs) (→‎Factory)
Jump to navigation Jump to search

Overview

Before starting off with design patterns for Ruby we need to define what a design pattern is, Design patterns can be described as "a general reusable solution to a commonly occurring problem in software design." [1] The idea of design patterns is to not to reinvent the wheel but to solve the current problems by using solutions that have worked in the past. A design pattern names, abstracts, and identifies the key aspects of a common design structure that make it useful for creating a reusable object-oriented design. It helps to identify the classes and instances and the way they collaborate with each other to form a solution to a problem. Design patterns c an be classified into 3 parts Creational, Structural, Behavioral (See if we can give links for these.)

Factory

Factories The factory design pattern is an object oriented design pattern. It is a creational design pattern and deals with the issues faced in creating objects. The main goal of this implementation is to isolate teh code that creates the class form the concete implementation of that class. Ruby example for the same is given below.


Example of Factory Code


class GearFactory
  def new() 
    if ( ... some condition )
       return Sprocket.new()
    else
       return Cog().new()
    end
  end
end

Our client class now becomes: class GearUser

 def doSomething(factory )
   ...
   my_gear = factory.new()
   ...
 end

end

The above code does not have to distinguish between a factory and an ordinary class. We can call the class using the followijng code. client.doSomething(GearFactory.new) # Use the factory client.doSomething(Cog) #Use the Cog class client.doSomething(Sprocket) #Use the Sprocket class