SlideShare uma empresa Scribd logo
1 de 11
Factory in Python
What is that crap

Define an interface for creating an object,
but let the subclasses decide which class to
instantiate.

The Factory method lets a class defer
instantiation to subclasses.
A Simple Diagram
Different Factory Types

    x   •Static
    x   •Polymorphic
    x   •Abstract
Static Factory
• Forces all the creation operations to be
  focused in one spot
                                  Static Factory:
                                      Shape
      Circle




      Square                         Product
class Shape(object):
   def factory(type):
     if type == "Circle" : return Circle()
     if type == "Square" : return Square()
     assert 1, "Bad shape creation " + type
   factory = staticmethod(factory)

class Circle(Shape):
   def draw(self): print "Circle.draw"
   def erase(self): print "Circle.erase"

class Square(Shape):
   def draw(self): print "Square.draw"
   def erase(self): print "Square.erase"

def shape_name_gen(n):
  types = Shape.__subclasses__()
  for i in range(n):
     yield random.choice(types).__name__
shapes = [Shape.factory(i) for i in shape_name_gen(7)]

for shape in shapes:
shape.draw()
shape.erase()
Polymorphic Factory
• Make a single superclass version of the method that calls a
  Factory Method to handle the instantiation
• The new class can be dynamically added to the factory
• Factory methods are in separate class as virtual function
• Different types of factories can be subclassed from the basic
  factory
class ShapeFactory:
   factories = {}
   def add_factory(id, shapefactory):
ShapeFactory.factories.put[id] = shapeFactory
add_factory = staticmethod(add_factory)

def create_shape(id):
     if not ShapeFactory.factories.has_key(id):
ShapeFactory.factories[id] = eval(id+'.Factory()')
     return ShapeFactory.factories[id].create()
create_shape = staticmethod(create_shape)

class Shape(object): pass

class Circle(Shape):                            def shape_name_gen(n):
   def draw(self): print "Circle.draw"            types = Shape.__subclasses__()
   def erase(self): print "Circle.erase"          for i in range(n):
class Factory:                                       yield random.choice(types).__name__
     def create(self): return Circle()
                                                shapes = [ShapeFactory.create_shape(i) 
class Square(Shape):                                for i in shape_name_gen(7)]
   def draw(self): print "Square.draw"
   def erase(self): print "Square.erase"        for shape in shapes:
   class Factory:                               shape.draw()
      def create(self): return Square()         shape.erase()
Abstract Factory
• The client creates a concrete
  implementation of the
  abstract factory and then
  uses the generic interface to
  create object
• The idea is that at the point
  of creation of the factory
  object, you decide how all the
  objects created by that
  factory will be used.
class Obstacle: pass                    class GameElementFactory: pass
class Player: pass
                                        class JavAndPuzzle(GameElementFactory):
class Jav(Player):                         def make_player(self): return Jav()
   def interact_with(self, obstacle):      def make_obstacle(self): return Puzzle()
print("Jav is playing a" )
obstacle.action()                       class
                                        BenAndWeapon(GameElementFactory):
class Ben(Player):                         def make_player(self): return Ben()
   def interact_with(self, obstacle):      def make_obstacle(self): return Weapon()
print("Ben is playing a " )             class GameEnvironment:
obstacle.action()                          def __init__(self, factory):
                                        self.factory = factory
class Puzzle(Obstacle):                 self.p = factory.make_player()
   def action(self):                    self.ob = factory.make_obstacle()
print("Puzzle")
                                          def play(self):
class Weapon(Obstacle):                 self.p.interact_with(self.ob)
   def action(self):
print("Weapon")                         g1 = GameEnvironment(JavAndPuzzle())
                                        g2 = GameEnvironment(BenAndWeapon())
                                        g1.play()
                                        g2.play()
Limitations of Factory
• The first limitation is that refactoring an
  existing class to use factories breaks existing
  clients.

Mais conteúdo relacionado

Semelhante a Factory in python

Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonTendayi Mawushe
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)Jacek Laskowski
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Python Yield
Python YieldPython Yield
Python Yieldyangjuven
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocksAyla Khan
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My PatienceAdam Lowry
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
2011 py con
2011 py con2011 py con
2011 py conEing Ong
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsMichael Heron
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
Why you should use super() though it sucks
Why you should use super() though it sucksWhy you should use super() though it sucks
Why you should use super() though it sucksEunchong Yu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Can someone please explain what the code below is doing and comment on.pdf
Can someone please explain what the code below is doing and comment on.pdfCan someone please explain what the code below is doing and comment on.pdf
Can someone please explain what the code below is doing and comment on.pdfkuldeepkumarapgsi
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocolrocketcircus
 

Semelhante a Factory in python (20)

Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
(map Clojure everyday-tasks)
(map Clojure everyday-tasks)(map Clojure everyday-tasks)
(map Clojure everyday-tasks)
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Python Yield
Python YieldPython Yield
Python Yield
 
Unit tests and mocks
Unit tests and mocksUnit tests and mocks
Unit tests and mocks
 
Testing My Patience
Testing My PatienceTesting My Patience
Testing My Patience
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
2011 py con
2011 py con2011 py con
2011 py con
 
PATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design PatternsPATTERNS02 - Creational Design Patterns
PATTERNS02 - Creational Design Patterns
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Why you should use super() though it sucks
Why you should use super() though it sucksWhy you should use super() though it sucks
Why you should use super() though it sucks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Can someone please explain what the code below is doing and comment on.pdf
Can someone please explain what the code below is doing and comment on.pdfCan someone please explain what the code below is doing and comment on.pdf
Can someone please explain what the code below is doing and comment on.pdf
 
Unit testing
Unit testingUnit testing
Unit testing
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 

Último

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

Último (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Factory in python

  • 2. What is that crap Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.
  • 4. Different Factory Types x •Static x •Polymorphic x •Abstract
  • 5. Static Factory • Forces all the creation operations to be focused in one spot Static Factory: Shape Circle Square Product
  • 6. class Shape(object): def factory(type): if type == "Circle" : return Circle() if type == "Square" : return Square() assert 1, "Bad shape creation " + type factory = staticmethod(factory) class Circle(Shape): def draw(self): print "Circle.draw" def erase(self): print "Circle.erase" class Square(Shape): def draw(self): print "Square.draw" def erase(self): print "Square.erase" def shape_name_gen(n): types = Shape.__subclasses__() for i in range(n): yield random.choice(types).__name__ shapes = [Shape.factory(i) for i in shape_name_gen(7)] for shape in shapes: shape.draw() shape.erase()
  • 7. Polymorphic Factory • Make a single superclass version of the method that calls a Factory Method to handle the instantiation • The new class can be dynamically added to the factory • Factory methods are in separate class as virtual function • Different types of factories can be subclassed from the basic factory
  • 8. class ShapeFactory: factories = {} def add_factory(id, shapefactory): ShapeFactory.factories.put[id] = shapeFactory add_factory = staticmethod(add_factory) def create_shape(id): if not ShapeFactory.factories.has_key(id): ShapeFactory.factories[id] = eval(id+'.Factory()') return ShapeFactory.factories[id].create() create_shape = staticmethod(create_shape) class Shape(object): pass class Circle(Shape): def shape_name_gen(n): def draw(self): print "Circle.draw" types = Shape.__subclasses__() def erase(self): print "Circle.erase" for i in range(n): class Factory: yield random.choice(types).__name__ def create(self): return Circle() shapes = [ShapeFactory.create_shape(i) class Square(Shape): for i in shape_name_gen(7)] def draw(self): print "Square.draw" def erase(self): print "Square.erase" for shape in shapes: class Factory: shape.draw() def create(self): return Square() shape.erase()
  • 9. Abstract Factory • The client creates a concrete implementation of the abstract factory and then uses the generic interface to create object • The idea is that at the point of creation of the factory object, you decide how all the objects created by that factory will be used.
  • 10. class Obstacle: pass class GameElementFactory: pass class Player: pass class JavAndPuzzle(GameElementFactory): class Jav(Player): def make_player(self): return Jav() def interact_with(self, obstacle): def make_obstacle(self): return Puzzle() print("Jav is playing a" ) obstacle.action() class BenAndWeapon(GameElementFactory): class Ben(Player): def make_player(self): return Ben() def interact_with(self, obstacle): def make_obstacle(self): return Weapon() print("Ben is playing a " ) class GameEnvironment: obstacle.action() def __init__(self, factory): self.factory = factory class Puzzle(Obstacle): self.p = factory.make_player() def action(self): self.ob = factory.make_obstacle() print("Puzzle") def play(self): class Weapon(Obstacle): self.p.interact_with(self.ob) def action(self): print("Weapon") g1 = GameEnvironment(JavAndPuzzle()) g2 = GameEnvironment(BenAndWeapon()) g1.play() g2.play()
  • 11. Limitations of Factory • The first limitation is that refactoring an existing class to use factories breaks existing clients.