Skip to content

Instantly share code, notes, and snippets.

@matsumonkie
Created August 3, 2014 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsumonkie/cb2072291fc0b1107fd9 to your computer and use it in GitHub Desktop.
Save matsumonkie/cb2072291fc0b1107fd9 to your computer and use it in GitHub Desktop.
null object pattern
class NullObject
def method_missing(*)
self
end
def respond_to_method_missing?(name)
true
end
def nil?
true
end
end
class NullEngine < NullObject
def start
puts "null engine cannot start"
end
end
def Actual(object)
case object
when NullObject then nil
else object
end
end
class Car
def initialize(engine = NullEngine.new())
@engine = engine
end
def run
@engine.start()
@engine.run()
end
def engine
Actual(@engine)
end
end
def main
car = Car.new()
car.run()
engine = car.engine
if engine
puts engine.description
end
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment