CSC/ECE 517 Fall 2011/ch4 4h sv

From Expertiza_Wiki
Jump to navigation Jump to search

Design Patterns in Ruby

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.

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

class Logger
 def initialize
   @log = File.open("log.txt", "a")
 end
  
 @@instance = Logger.new

 def self.instance
   return @@instance
 end

 def log(msg)
   @log.puts(msg)
 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.

require 'singleton'
class Example
include Singleton
attr_accessor :val
end
r = Registry.new #throws a NoMethodError
r = Registry.instance
r.val = 5
s = Registry.instance
puts s.val >>
s.val = 6
puts r.val >>
s.dup >>

Adapter Pattern

An adapter allows classes to work together that normally could not because of incompatible interfaces.

  • It “wraps” its own interface around the interface of a pre-existing

class. What does this mean?

  • It may also translate data formats from the caller to a form needed by

the callee.

class SquarePeg
attr_reader :width
def initialize(width)
@width = width
end
end
class RoundPeg
attr_reader :radius
def initialize(r

Command Pattern

Strategy Pattern

References

http://designpatternsinruby.com/section01/article.html