Python - Factory Pattern example


Here is an example of Factory pattern in Python. I have done similar in C# many times and I figured I would try to accomplish something like this in Python as I am learning it. Please ignore the casing on my variable names as I am still learning the proper Python syntax :)


#!/usr/bin/python

###############################################################################

class AddressVerification:
    def __init__(self, name):  # Constructor of the class
        self.name = name

    def talk(self):  # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")


###############################################################################

###############################################################################

class ABCProviderAddressVerification(AddressVerification):
    def talk(self):
        return 'ABC Provider performing...!'

###############################################################################
###############################################################################

class EFGProviderAddressVerification(AddressVerification):
    def talk(self):
        return 'EFG Provider performing ...'

###############################################################################

###############################################################################

class AddressVerifyFactory:
    def __init__(self, defaultProviderName):
        self.DefaultProviderName = defaultProviderName
        self.AddressVerifyObj = 0
        providerFromConfig = self.DefaultProviderName

        if providerFromConfig == '1':
            print 'provider is 1'
            self.AddressVerifyObj = ABCProviderAddressVerification('provider 1')
        else:
            print 'provider is 2'            
            self.AddressVerifyObj = EFGProviderAddressVerification('provider 2')

    def PerformAddressVerification(self):
        print 'Start of PerformAddressVerification method'
        print self.AddressVerifyObj.talk()


###############################################################################

###############################################################################

def main():
    addr_obj = AddressVerifyFactory('1')
    addr_obj.PerformAddressVerification()

    address_object2 = AddressVerifyFactory('2')
    address_object2.PerformAddressVerification()



###############################################################################


if __name__ == "__main__": main()



OUTPUT:

provider is 1
Start of PerformAddressVerification method
ABC Provider performing...!
provider is 2
Start of PerformAddressVerification method
EFG Provder performing ...



almirsCorner.com

#python #programming #code #coding #software #softwaredeveloper #softwareengineering #programmer

No comments:

Post a Comment