Skip to content

Instantly share code, notes, and snippets.

@jasper-lyons
Last active January 4, 2016 02:49
Show Gist options
  • Save jasper-lyons/8557701 to your computer and use it in GitHub Desktop.
Save jasper-lyons/8557701 to your computer and use it in GitHub Desktop.
Creational Design Patterns in Python: Abstract Factory
########## The Factory's base class #########
class AbstractFactory(object):
def create_product(self, **args):
raise NotImplementedError("Requires derived factory class for implementation.")
######### The class of the object that needs creating ###########
class Product(object):
def do_somthing(self):
print "Doing some things!"
######### The Factory of the class that needs creating ###########
class ConcreteFactory(AbstractFactory):
def create_product(self):
return Product()
######### The class that needs a product ###########
class Client(object):
def __init__(self, factory):
self.factory = factory
def use_a_product(self):
product = self.factory.create_product()
product.do_somthing()
######## Start le program #########
def main():
factory = ConreteFactory()
client = Client(factory)
client.use_a_product()
######## Catch the start of the Program ########
if __name__ == "__main__":
main()
@jasper-lyons
Copy link
Author

Python doesn't really need an abstract class since it has duck typing and the AbstractFactory class would only exist to allow many different derivatives to be used in it's place. This is really only applicable in stictly typed languages.

That is not to say that the factory method isn't useful in python as isolating your creation of new instances does allow one to easily swap them in and out for mocks in unit tests. It also allows a clear and well known method for implementing new 'products' for the 'client' to use. The importance of this is that it is such a well known pattern it will be almost transparent interface for other developer working on the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment