User Tools

Site Tools


python:factorypat

Factory Pattern in Python using ABC (Abstract Base Classes)

04.05.2010

The purpose of the factory pattern is to help you with loose coupling between different parts of a system. Instead of creating directly objects for your classes, we implement a central place who will return the new instances.

Below, ILog - abstract base class, ErrorLog and NoticeLog derivated class based on ILog (take a look at ILog.register method), and LogFactory class.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       factory.py
 
import sys
import abc
 
class ILog(object):
    __metaclass__ = abc.ABCMeta
 
    @abc.abstractmethod
    def saveLogMessage(self, msg):
        '''abstract method to save to db'''
        return 
 
    @abc.abstractmethod
    def echoLogMessage(self, msg):
        '''abstract method to print on screen'''
        return
 
 
class ErrorLog(object):
    def echoLogMessage(self, msg):
        print "MESSAGE[ERROR]: %s" % msg
    def saveLogMessage(self, msg):
        pass
 
 
class NoticeLog(object):
    def echoLogMessage(self, msg):
        print "MESSAGE[NOTICE]: %s" % msg
    def saveLogMessage(self, msg):
        pass
 
 
class LogFactory:
    @staticmethod
    def factory(type):
        for subclass in ILog._abc_registry:
            if (subclass.__name__ == type):
                return subclass()
        raise Exception, 'Class %s not found' % type
 
 
 
ILog.register(ErrorLog)
ILog.register(NoticeLog)
 
if __name__ == '__main__':
    try:
        LogFactory.factory("ErrorLog").echoLogMessage("test error message")
        LogFactory.factory("NoticeLog").echoLogMessage("test notice message")
    except Exception, e:
        print e

python/factorypat.txt · Last modified: 2013/03/16 17:40 (external edit)