CSC/ECE 517 Fall 2012/ch1b 1w42 js: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 301: Line 301:
=See Also=
=See Also=


[http://www.oodesign.com 1. Object Oriented Design]
* [http://www.oodesign.com Object Oriented Design]


[http://en.wikipedia.org/wiki/Object-oriented_programming 2. Object - Oriented Programming]
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object - Oriented Programming]


[http://c2c.com 3. More Object oriented Programming]
* [http://c2c.com More Object oriented Programming]


==References==
* [http://designpatternsinruby.com/section01/article.html Article on Design Patterns in Ruby]


[http://designpatternsinruby.com/section01/article.html 1. Article on Design Patterns in Ruby]
* [http://www.uml.org.cn/c++/pdf/DesignPatterns.pdf Design Patterns - Elements of Reusable Object Oriented Software by Erich Gamma]  


[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 Wiki - Singleton Pattern]


[http://en.wikipedia.org/wiki/Singleton_pattern 3. Wiki - Singleton Pattern]
* [http://en.wikipedia.org/wiki/Adapter_pattern Wiki - Adapter Pattern]


[http://en.wikipedia.org/wiki/Adapter_pattern 4. Wiki - Adapter Pattern]
* [http://en.wikipedia.org/wiki/Command_pattern Wiki - Command Pattern]


[http://en.wikipedia.org/wiki/Command_pattern 5. Wiki - Command Pattern]
* [http://en.wikipedia.org/wiki/Strategy_pattern Wiki - Strategy Pattern]


[http://en.wikipedia.org/wiki/Strategy_pattern 6. Wiki - Strategy Pattern]
* [http://en.wikipedia.org/wiki/Closure_(computer_science) Wiki - Closures]


[http://en.wikipedia.org/wiki/Closure_(computer_science) 7. Wiki - Closures]
* [http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf Lec 13 - Class Notes]


[http://courses.ncsu.edu/csc517//common/lectures/notes/lec13.pdf 8. Lec 13 - Class Notes]
* [http://www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt State and Strategy Pattern]


[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 Command Pattern]


[http://www.codeproject.com/KB/architecture/commandpatterndemo.aspx 9. Command Pattern]
=References=
<references />

Revision as of 09:31, 3 October 2012

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 is a general reusable solution to a commonly occurring problem within a given context in software design

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.

  • Factory Pattern, which allows a class to defer instantiation to subclasses.
  • Abstract Factory Pattern, which provides an interface for creating related or dependent objects without specifying the objects' concrete classes.
  • Builder Pattern, which separates the construction of a complex object from its representation so that the same construction process can create different representation.
  • Prototype Pattern, which specifies the kind of object to create using a prototypical instance, and creates new objects by cloning this prototype.
  • Singleton Pattern, which ensures that only one instance of a class is created and provides a global access point to the object.

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

  • Adapter Pattern, which 'adapts' one interface for a class into one that a client expects.
  • Bridge Pattern, which decouples an abstraction from its implementation so that the two can vary independently.
  • Composite Pattern: a tree structure of objects where every object has the same interface.
  • Decorator Pattern, adds additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes
  • Facade Pattern, creates a simplified interface of an existing interface to ease usage for common tasks.
  • Flyweight Pattern: a high quantity of objects share a common properties object to save space.
  • Proxy Pattern: a class functioning as an interface to another thing.

Behavioral Pattern, which are concerned with communication between objects.

  • Command Pattern, which enables to pass around the code that needs to be executed later.
  • Chain of Responsibility Pattern: Command objects are handled or passed on to other objects by logic-containing processing objects.
  • Interpreter Pattern, implements a specialized computer language to rapidly solve a specific set of problems.
  • Iterator Pattern: Iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation.
  • Mediator Pattern, which provides a unified interface to a set of interfaces in a subsystem.
  • Momento Pattern, which provides the ability to restore an object to its previous state (rollback).
  • Observer Pattern: Publish/Subscribe or Event Listener. Objects register to observe an event that may be raised by another object
  • State Pattern: A clean way for an object to partially change its type at runtime.
  • Strategy Pattern: Algorithms can be selected on the fly.
  • Template Pattern, which describes the program skeleton of a program.
  • Visitor Pattern: A way to separate an algorithm from an object.

Some of the Patterns that are more commonly used with Ruby are explained below.

Creational Pattern

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.

Need better definition.

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'

'What is meant by Some kind of error is expected? Content here is good, will need to rephrase.'

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.

Rephrase again. Not formal enough

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 snippet shows that our class 'behaves' like a singleton. We have a '.instance' method defined 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.

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.

Structural 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 a compatible interface.
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.

Lets look at a simple example.<ref>Olsen, R. (2007). Filling in the gaps with the adapter. In Design patterns in ruby (pp. 164-165). Addison Wesley.</ref>

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.

class Encrypter
  def initialize(key)
    @key = key 
  end
  def encrypt(reader, writer)
    key_index = 0
    while not reader.eof?
      clear_char = reader.getc
      encrypted_char = clear_char ^ @key[key_index]
      writer.putc(encrypted_char)
      key_index = (key_index + 1) % @key.size
    end 
  end
end

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.

So, we will define a StringIOAdapter class:

class StringIOAdapter
  def initialize(string)
    @string = string
    @position = 0
  end
  def getc
    if @position >= @string.length
      raise EOFError
    end
    ch = @string[@position]
    @position += 1
    return ch
  end
  def eof?
    return @position >= @string.length
  end 
end

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.

To use Encrypter with StringIOAdapter, the reader input object is defined to be of type StringIOAdapter.

encrypter = Encrypter.new('OOLS')
reader= StringIOAdapter.new('TA position open with Prof. XYZ')
writer=File.open('out.txt', 'w')
encrypter.encrypt(reader, writer)

Thus the Adapter bridges the chasm between the interface you have and the interface you need.

The class diagram of Adapter class is usually given as:

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.

Behavioral Patterns

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.

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?

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.

This is not much use without a code example

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.

We could also add a section on drawbacks of design patterns. I found a link on that.

See Also

References

<references />