Published: Sept. 5, 2019 by lukemakin |  estimated reading time: 16 minutes
Factory design pattern is responsible for the creation of new objects without specifying particular classes. The concept is to create a seperate static method (we will call ours simply "factory"), that will take a string value as an input and deliver type of class to be returned as an output. To analyze how this works we will go through an combat game example - we will create random characters as heroes fighting evil enemies.

First let's create an Abstract Base Class (ABC) that allows us to define abstract methods which later will have to be overriden within each class that inherits from ABC.

from copy import deepcopy
import random
from abc import ABC, abstractmethod

class Character(ABC):
@abstractmethod
def __init__(self):
self.__hit_points = None
self.__health_points = None

@abstractmethod
def set_hit_points(self):
pass

@abstractmethod
def set_health_points(self):
pass

@abstractmethod
def get_info(self):
pass

Next let's create a Hero class which will contain the factory method:


class Hero:

power_bonus = {
'magic': 2,
'punches and kicks': 5,
'steal armor': 0,
'giant paws' : 3,
}

defense_bonus = {
'magic': 4,
'punches and kicks': 1,
'steal armor': 7,
'giant paws' : 2,
}

heros = ['Magician', 'Fighter', 'Robot', 'Bear']

@staticmethod
def get_hero():
return random.choice(Hero.heros)

@staticmethod
def factory(type, name):
if type == 'Magician':
return Magician(name)
elif type == 'Fighter':
return Fighter(name)
elif type == 'Robot':
return Robot(name)
elif type == 'Bear':
return Bear(name)
else:
return None

So above we have defined power and defense bonuses (depending on the hero type), next we can see a hero list and a static method to get random hero. Finally we have our factory method, that will create an specific hero object.

Let's take a look at the rest of the code with classes inheriting from Hero class:

class Magician(Character, Hero):

def __init__(self, name):
Character.__init__(self)
self.__name = name
self.__power = 'magic'

def set_new_special_power(self, power):
self.__power = power

def set_hit_points(self):
points = random.randint(5,7)
self.__hit_points = points

def set_health_points(self):
points = random.randint(45,55)
self.__health_points = points

def get_info(self):
print('========== INFO ==========')
print(f"Special Power: {self.__power}")
print(f"Hit points: {self.__hit_points}")
print(f"Health points: {self.__health_points}")

def get_power_bonus(self):
return Hero.power_bonus.get(self.__power)


class Fighter(Character, Hero):

def __init__(self, name):
Character.__init__(self)
self.__name = name
self.__power = 'punches and kicks'

def set_new_special_power(self, power):
self.__power = power

def set_hit_points(self):
points = random.randint(5,7)
self.__hit_points = points

def set_health_points(self):
points = random.randint(45,55)
self.__health_points = points

def get_info(self):
print('========== INFO ==========')
print(f"Special Power: {self.__power}")
print(f"Hit points: {self.__hit_points}")
print(f"Health points: {self.__health_points}")

class Robot(Hero):

def __init__(self, name):
Character.__init__(self)
self.__name = name
self.__power = 'steal armor'

def set_new_special_power(self, power):
self.__power = power

def set_hit_points(self):
points = random.randint(5,7)
self.__hit_points = points

def set_health_points(self):
points = random.randint(45,55)
self.__health_points = points

def get_info(self):
print('========== INFO ==========')
print(f"Special Power: {self.__power}")
print(f"Hit points: {self.__hit_points}")
print(f"Health points: {self.__health_points}")

class Bear(Hero):

def __init__(self, name):
Character.__init__(self)
self.__name = name
self.__power = 'giant paws'

def set_new_special_power(self, power):
self.__power = power

def set_hit_points(self):
points = random.randint(5,7)
self.__hit_points = points

def set_health_points(self):
points = random.randint(45,55)
self.__health_points = points

def get_info(self):
print('========== INFO ==========')
print(f"Special Power: {self.__power}")
print(f"Hit points: {self.__hit_points}")
print(f"Health points: {self.__health_points}")

To finish this article, let's try out this code and see the results:


obj = Hero()
hero = Hero.get_hero()
hero_obj = obj.factory(hero, 'my name')

hero_obj.set_hit_points()
hero_obj.set_health_points()
hero_obj.get_info()

'''
========== INFO ==========
Special Power: steal armor
Hit points: 7
Health points: 47
'''

This is it! For logged in users in "extras" a sample of Enemy class.

 
Extras
To view additional content login or create a free account
Categories:
Share your thoughts

No comments yet...

Signup to the newsletter
To get the latest updates from pyplane
© copyright 2019 pyplane.com