Jul-30-2019, 10:27 PM
All,
I am looking for guidance on what would be good design pattern to use / implement given a particular problem.
Problem Statement:
Let us say we would like to define a class that defines i-phone. Please note the below example is only for illustration.
If a user of this class wants to determine the mfg.year which is only set in the sub-class, what is the best way to get that information, without knowing which sub-class to call.
The user is always only going to instantiate the base class that is of the IPhone().
One way I can think of addressing this problem is by doing the following:
I am looking for guidance on what would be good design pattern to use / implement given a particular problem.
Problem Statement:
Let us say we would like to define a class that defines i-phone. Please note the below example is only for illustration.
If a user of this class wants to determine the mfg.year which is only set in the sub-class, what is the best way to get that information, without knowing which sub-class to call.
The user is always only going to instantiate the base class that is of the IPhone().
class IPhone():
def __init__(self,ver):
self.ver = ver
self.phone_factory()
def phone_factory(self):
if self.ver == '3G':
return IPhone3G()
elif self.ver == '3GS':
return IPhone3GS()
elif self.ver == '4':
return IPhone4()
elif self.ver == '4s':
return IPhone4s()
elif self.ver == '5':
return IPhone5()
else:
pass
class IPhone3G():
def __init__(self):
self.year = 2007
class IPhone3GS():
def __init__(self):
self.year = 2009
class IPhone4():
def __init__(self):
self.year = 2010
class IPhone4s():
def __init__(self):
self.year = 2011
class IPhone5():
def __init__(self):
self.year = 2012Potential Solution: One way I can think of addressing this problem is by doing the following:
class IPhone():
def __init__(self,ver):
self.ver = ver
self.phone_factory()
def phone_factory(self):
if self.ver == '3G':
t = IPhone3G()
self.year = t.year
elif self.ver == '3GS':
t = IPhone3GS()
self.year = t.year
elif self.ver == '4':
t = IPhone4()
self.year = t.year
elif self.ver == '4s':
t = IPhone4s()
self.year = t.year
elif self.ver == '5':
t = IPhone5()
self.year = t.year
else:
pass
class IPhone3G():
def __init__(self):
self.year = 2007
class IPhone3GS():
def __init__(self):
self.year = 2009
class IPhone4():
def __init__(self):
self.year = 2010
class IPhone4s():
def __init__(self):
self.year = 2011
class IPhone5():
def __init__(self):
self.year = 2012But, is this a good approach ? I have looked at class methods and static methods as alternative options but I am not really sure what is the best approach. Can anybody advice?
