|
| 1 | +# |
| 2 | +# Python Design Patterns: Factory Method |
| 3 | +# Author: Jakub Vojvoda [github.com/JakubVojvoda] |
| 4 | +# 2016 |
| 5 | +# |
| 6 | +# Source code is licensed under MIT License |
| 7 | +# (for more details see LICENSE) |
| 8 | +# |
| 9 | + |
| 10 | +import sys |
| 11 | + |
| 12 | +# |
| 13 | +# Product |
| 14 | +# products implement the same interface so that the classes |
| 15 | +# can refer to the interface not the concrete product |
| 16 | +# |
| 17 | +class Product: |
| 18 | + def getName(self): |
| 19 | + pass |
| 20 | + |
| 21 | +# |
| 22 | +# Concrete Products |
| 23 | +# define product to be created |
| 24 | +# |
| 25 | +class ConcreteProductA(Product): |
| 26 | + def getName(self): |
| 27 | + return "type A" |
| 28 | + |
| 29 | +class ConcreteProductB(Product): |
| 30 | + def getName(self): |
| 31 | + return "type B" |
| 32 | + |
| 33 | +# |
| 34 | +# Creator |
| 35 | +# contains the implementation for all of the methods |
| 36 | +# to manipulate products except for the factory method |
| 37 | +# |
| 38 | +class Creator: |
| 39 | + def createProductA(self): |
| 40 | + pass |
| 41 | + |
| 42 | + def createProductB(self): |
| 43 | + pass |
| 44 | + |
| 45 | +# |
| 46 | +# Concrete Creator |
| 47 | +# implements factory method that is responsible for creating |
| 48 | +# one or more concrete products ie. it is class that has |
| 49 | +# the knowledge of how to create the products |
| 50 | +# |
| 51 | +class ConcreteCreator(Creator): |
| 52 | + def createProductA(self): |
| 53 | + return ConcreteProductA() |
| 54 | + |
| 55 | + def createProductB(self): |
| 56 | + return ConcreteProductB() |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + creator = ConcreteCreator() |
| 61 | + |
| 62 | + p1 = creator.createProductA() |
| 63 | + print("Product: " + p1.getName()) |
| 64 | + |
| 65 | + p2 = creator.createProductB() |
| 66 | + print("Product: " + p2.getName()) |
0 commit comments