Reading Time: 1 minutes
Factory Design Pattern in Python
Write a Python program to implement Factory Design Pattern.
Factory
# Different classes denoting different types of objects having a common characteristic: Knight, Rook & Bishop
class Rook:
'''A simple Rook class'''
def move(self):
return "I move any number of spaces but only horizontally or vertically."
class Knight:
'''A simple Knight class'''
def move(self):
return "I move 2 and half spaces."
class Bishop:
'''A simple Bishop class'''
def move(self):
return "I move any number of spaces diagonally."
# A Factory Method that returns the object based on an input.
def makeChessPiece(piece):
'''Factory method that takes a string and returns an object based on it.'''
pieces = {"knight": Knight(), "bishop": Bishop(), "rook": Rook()}
return pieces[piece]
class ChessPieceFactory:
def createChessPiece(self, inputString):
createdPiece = makeChessPiece(inputString)
return createdPiece
chessPieceFactory = ChessPieceFactory()
pieceOne = chessPieceFactory.createChessPiece('knight')
print("Knight:", pieceOne.move())
pieceTwo = chessPieceFactory.createChessPiece('bishop')
print("Bishop:", pieceTwo.move())
pieceThree = chessPieceFactory.createChessPiece('rook')
print("Rook:", pieceThree.move())
### OUTPUT ###
Knight: I move 2 and half spaces.
Bishop: I move any number of spaces diagonally.
Rook: I move any number of spaces but only horizontally or vertically.







