Some Design Patterns In Ruby. Just because you have duck-typing doesn't mean
you can ignore common OO idioms! (c) 2012 Abram Hindle and Ken Wong ...
Some Design Patterns In Ruby
Just because you have duck-typing doesn't mean you can ignore common OO idioms!
https://github.com/abramhindle/ruby-design-patterns http://softwareprocess.es
[email protected]
(c) 2012 Abram Hindle and Ken Wong CC-BY-SA 3.0
Singleton Pattern ●
Restrict instatiation of a class to 1 object.
●
Allow only 1 instance of a class.
●
Like a global, but hopefully less mutable.
●
Can be lazily instantiated
●
Much maligned.
Singleton Pattern ●
Necessary UML MySingleton Creates and Limits access
Instance: MySingleton
getInstance(): MySingleton
Square boxes are for suckers
Singleton Pattern ●
In Ruby you generally limit access via a gentleman's agreement we won't peak the guts. –
●
I think we should avoid overcomplicating things and stick to this agreement. # http://apidock.com/ruby/Module/private_class_method # http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again class MySingleton # attempt to limit access to the constructor private_class_method :new # class variable instance @@instance = nil def self.instance() if (@@instance.nil?()) # self. and MySingleton tend not to work @@instance = self.new() end return @@instance end end
Singleton ●
There are many more ways to make a singleton
●
The singleton module is pretty useful require 'singleton' # http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again class IncSingleton include Singleton end
Singleton Resources ●
●
●
●
Ruby Singleton Pattern Again http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again Dalibor Nasevic Singleton Pattern http://c2.com/cgi/wiki?SingletonPattern Singleton Pattern http://en.wikipedia.org/wiki/Singleton_pattern Method private_class_method http://apidock.com/ruby/Module/private_class_method
Composite Pattern ●
Design intent: –
to compose individual objects to build up a tree structure ●
●
The individual objects and the composed objects are treated uniformly –
●
e.g., a folder can contain files and other folders
e.g., files and folders both have a name or a size
Each object is responsible for answering its own query.
“Recursive (De)composition” a Folder
a File
a Folder
a Folder
a File
a File
a File
a File
a Folder
8
Composite Example Structure NamedSizedItem
0..*
+getSize(): int
File
Folder
9
Composite Example Structure Component
0..*
+action(): value
Leaf
Composite
10
Composite Code class NamedSizedItem @name = nil @size = 0 def initialize(name) @name = name end def name() return @name end def size() return @size end end class NamedFile < NamedSizedItem def initialize(name) @name = name @size = 1 end end
class NamedFolder < NamedSizedItem @files = [] def initialize(name) @name = name @files = [] end def addFile(file) @files