Created
August 3, 2014 08:52
-
-
Save matsumonkie/cb2072291fc0b1107fd9 to your computer and use it in GitHub Desktop.
null object pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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