"The Gang of Four"
(1995)
Abstract Factory
Builder
Factory Method
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Chain of responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template
Visitor
class SquarePeg
attr_reader :width
def initialize(width)
@width = width
end
end
class RoundPeg
attr_reader :radius
def initialize(radius)
@radius = radius
end
end
class RoundHole
attr_reader :radius
def initialize(radius)
@radius = radius
end
def peg_fits?(peg)
peg.radius <= radius
end
end
round_hole = RoundHole.new(10)
round_peg = RoundPeg.new(8)
round_hole.peg_fits?(round_peg)
# => true
square_peg = SquarePeg.new(8)
round_hole.peg_fits?(square_peg)
# => NoMethodError: undefined method `radius' for #<SquarePeg:0x007ff9f108fb68 @width=8>
class SquarePegAdaptor
def initialize(square_peg)
@peg = square_peg
end
def radius
Math.sqrt(((@peg.width / 2) ** 2) * 2)
end
end
round_hole = RoundHole.new(4.0)
4.upto(7) do |i|
peg = SquarePegAdaptor.new(SquarePeg.new(i))
puts "Square peg of size #{i} fits: #{round_hole.peg_fits?(peg)}"
end
# Square peg of size 4 fits: true
# Square peg of size 5 fits: true
# Square peg of size 6 fits: false
# Square peg of size 7 fits: false
require 'net/http'
require 'uri'
url = URI.parse('http://www.google.com')
res = Net::HTTP.start(url.host, url.port) do |http|
http.get('/index.html')
end
puts res.body
require "open-uri"
puts open("http://www.google.com").read
DSLs (Sinatra, RSpec) - Facade pattern
Ruby symbols - Flyweight pattern
Rack middleware - Decorator pattern
jQuery - Observer pattern
ActiveRecord - Adapter pattern
ActiveRecord - ActiveRecord pattern
Computer Science is a science of abstraction - creating the right model for a problem and devising the appropriate mechanizable techniques to solve it."
A. Aho and J. Ullman, 1992
"Programs must be written for people to read, and only incidentally for machines to execute."
H. Abelson and G. Sussman, 1985
with huge thanks to Henry Garner for open sourcing his original presentation