Created
June 28, 2013 10:37
-
-
Save mathie/5883835 to your computer and use it in GitHub Desktop.
Using .new as a factory method. Good idea or crazy?
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 SerialNumber | |
def self.new(str = nil) | |
# Our new method is really a factory to one of the concrete subclasses. | |
if SerialNumber == self | |
if str.blank? | |
nil | |
# Zigbee serial numbers are easy to spot; they start with eight '0's. | |
elsif str.strip =~ /^00000000/ | |
ZigbeeSerialNumber.new(str) | |
else | |
FtdiSerialNumber.new(str) | |
end | |
else | |
super | |
end | |
end | |
# general implementation | |
end | |
class FtdiSerialNumber < SerialNumber | |
# overridden implementation | |
end | |
class ZigbeeSerialNumber < SerialNumber | |
# overridden implementation | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment