Python Design Patterns – Strategy

Python Design Patterns – Strategy ”; Previous Next The strategy pattern is a type of behavioral pattern. The main goal of strategy pattern is to enable client to choose from different algorithms or procedures to complete the specified task. Different algorithms can be swapped in and out without any complications for the mentioned task. This pattern can be used to improve flexibility when external resources are accessed. How to implement the strategy pattern? The program shown below helps in implementing the strategy pattern. import types class StrategyExample: def __init__(self, func = None): self.name = ”Strategy Example 0” if func is not None: self.execute = types.MethodType(func, self) def execute(self): print(self.name) def execute_replacement1(self): print(self.name + ”from execute 1”) def execute_replacement2(self): print(self.name + ”from execute 2”) if __name__ == ”__main__”: strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1) strat1.name = ”Strategy Example 1” strat2 = StrategyExample(execute_replacement2) strat2.name = ”Strategy Example 2” strat0.execute() strat1.execute() strat2.execute() Output The above program generates the following output − Explanation It provides a list of strategies from the functions, which execute the output. The major focus of this behavior pattern is behavior. Print Page Previous Next Advertisements ”;

Python Design Patterns – Observer

Python Design Patterns – Observer ”; Previous Next In this pattern, objects are represented as observers that wait for an event to trigger. An observer attaches to the subject once the specified event occurs. As the event occurs, the subject tells the observers that it has occurred. The following UML diagram represents the observer pattern − How to implement the observer pattern? Let us now see how to implement the observer pattern. import threading import time import pdb class Downloader(threading.Thread): def run(self): print ”downloading” for i in range(1,5): self.i = i time.sleep(2) print ”unfunf” return ”hello world” class Worker(threading.Thread): def run(self): for i in range(1,5): print ”worker running: %i (%i)” % (i, t.i) time.sleep(1) t.join() print ”done” t = Downloader() t.start() time.sleep(1) t1 = Worker() t1.start() t2 = Worker() t2.start() t3 = Worker() t3.start() Output The above program generates the following output − Explanation The above code explains the procedure of downloading a particular result. As per the observer pattern logic, every object is treated as observer. It prints the output when event is triggered. Print Page Previous Next Advertisements ”;

Python Design Patterns – Iterator

Python Design Patterns – Iterator ”; Previous Next The iterator design pattern falls under the behavioral design patterns category. Developers come across the iterator pattern in almost every programming language. This pattern is used in such a way that it helps to access the elements of a collection (class) in sequential manner without understanding the underlying layer design. How to implement the iterator pattern? We will now see how to implement the iterator pattern. import time def fib(): a, b = 0, 1 while True: yield b a, b = b, a + b g = fib() try: for e in g: print(e) time.sleep(1) except KeyboardInterrupt: print(“Calculation stopped”) Output The above program generates the following output − If you focus on the pattern, Fibonacci series is printed with the iterator pattern. On forceful termination of user, the following output is printed − Explanation This python code follows the iterator pattern. Here, the increment operators are used to start the count. The count ends on forceful termination by the user. Print Page Previous Next Advertisements ”;

Exception Handling

Python Design Patterns – Exception Handling ”; Previous Next Handling exceptions is also a primary criterion of design patterns. An exception is an error that happens during the execution of a program. When a particular error occurs, it is important to generate an exception. This helps in curbing program crashes. Why use exceptions? Exceptions are convenient ways of handling errors and special conditions in a program. When a user thinks that the specified code can produce an error then it is important to use exception handling. Example – Division by zero import sys randomList = [”a”, 0, 2] for entry in randomList: try: print(“The entry is”, entry) r = 1/int(entry) break except: print(“Oops!”,sys.exc_info()[0],”occured.”) print(“Next entry.”) print() print(“The reciprocal of”,entry,”is”,r) Output The above program generates the following output − Raising Exceptions In Python programming specifically, exceptions are raised when corresponding error of code occurs at run time. This can be forcefully raised using the “raise” keyword. Syntax raise KeyboardInterrupt Traceback (most recent call last): … KeyboardInterrupt Print Page Previous Next Advertisements ”;

Python Design Patterns – Singleton

Python Design Patterns – Singleton ”; Previous Next This pattern restricts the instantiation of a class to one object. It is a type of creational pattern and involves only one class to create methods and specified objects. It provides a global point of access to the instance created. How to implement a singleton class? The following program demonstrates the implementation of singleton class where it prints the instances created multiple times. class Singleton: __instance = None @staticmethod def getInstance(): “”” Static access method. “”” if Singleton.__instance == None: Singleton() return Singleton.__instance def __init__(self): “”” Virtually private constructor. “”” if Singleton.__instance != None: raise Exception(“This class is a singleton!”) else: Singleton.__instance = self s = Singleton() print s s = Singleton.getInstance() print s s = Singleton.getInstance() print s Output The above program generates the following output − The number of instances created are same and there is no difference in the objects listed in output. Print Page Previous Next Advertisements ”;

Model View Controller Pattern

Model View Controller Pattern ”; Previous Next Model View Controller is the most commonly used design pattern. Developers find it easy to implement this design pattern. Following is a basic architecture of the Model View Controller − Let us now see how the structure works. Model It consists of pure application logic, which interacts with the database. It includes all the information to represent data to the end user. View View represents the HTML files, which interact with the end user. It represents the model’s data to user. Controller It acts as an intermediary between view and model. It listens to the events triggered by view and queries model for the same. Python code Let us consider a basic object called “Person” and create an MVC design pattern. Model.py import json class Person(object): def __init__(self, first_name = None, last_name = None): self.first_name = first_name self.last_name = last_name #returns Person name, ex: John Doe def name(self): return (“%s %s” % (self.first_name,self.last_name)) @classmethod #returns all people inside db.txt as list of Person objects def getAll(self): database = open(”db.txt”, ”r”) result = [] json_list = json.loads(database.read()) for item in json_list: item = json.loads(item) person = Person(item[”first_name”], item[”last_name”]) result.append(person) return result It calls for a method, which fetches all the records of the Person table in database. The records are presented in JSON format. View It displays all the records fetched within the model. View never interacts with model; controller does this work (communicating with model and view). from model import Person def showAllView(list): print ”In our db we have %i users. Here they are:” % len(list) for item in list: print item.name() def startView(): print ”MVC – the simplest example” print ”Do you want to see everyone in my db?[y/n]” def endView(): print ”Goodbye!” Controller Controller interacts with model through the getAll() method which fetches all the records displayed to the end user. from model import Person import view def showAll(): #gets list of all Person objects people_in_db = Person.getAll() #calls view return view.showAllView(people_in_db) def start(): view.startView() input = raw_input() if input == ”y”: return showAll() else: return view.endView() if __name__ == “__main__”: #running controller function start() Print Page Previous Next Advertisements ”;

Python Design Patterns – Factory

Python Design Patterns – Factory ”; Previous Next The factory pattern comes under the creational patterns list category. It provides one of the best ways to create an object. In factory pattern, objects are created without exposing the logic to client and referring to the newly created object using a common interface. Factory patterns are implemented in Python using factory method. When a user calls a method such that we pass in a string and the return value as a new object is implemented through factory method. The type of object used in factory method is determined by string which is passed through method. In the example below, every method includes object as a parameter, which is implemented through factory method. How to implement a factory pattern? Let us now see how to implement a factory pattern. class Button(object): html = “” def get_html(self): return self.html class Image(Button): html = “<img></img>” class Input(Button): html = “<input></input>” class Flash(Button): html = “<obj></obj>” class ButtonFactory(): def create_button(self, typ): targetclass = typ.capitalize() return globals()[targetclass]() button_obj = ButtonFactory() button = [”image”, ”input”, ”flash”] for b in button: print button_obj.create_button(b).get_html() The button class helps to create the html tags and the associated html page. The client will not have access to the logic of code and the output represents the creation of html page. Output Explanation The python code includes the logic of html tags, which specified value. The end user can have a look on the HTML file created by the Python code. Print Page Previous Next Advertisements ”;

Introduction

Python Design Patterns – Introduction ”; Previous Next Design patterns are used to represent the pattern used by developers to create software or web application. These patterns are selected based on the requirement analysis. The patterns describe the solution to the problem, when and where to apply the solution and the consequences of the implementation. Structure of a design pattern The documentation of design pattern is maintained in a way that focuses more on the technology that is used and in what ways. The following diagram explains the basic structure of design pattern documentation. Pattern Name It describes the pattern in short and effective manner. Intent/Motive It describes what the pattern does. Applicability It describes the list of situations where pattern is applicable. Participants and consequences Participants include classes and objects that participate in the design pattern with a list of consequences that exist with the pattern. Why Python? Python is an open source scripting language. It has libraries that support a variety of design patterns. The syntax of python is easy to understand and uses English keywords. Python provides support for the list of design patterns that are mentioned below. These design patterns will be used throughout this tutorial − Model View Controller Pattern Singleton pattern Factory pattern Builder Pattern Prototype Pattern Facade Pattern Command Pattern Adapter Pattern Prototype Pattern Decorator Pattern Proxy Pattern Chain of Responsibility Pattern Observer Pattern State Pattern Strategy Pattern Template Pattern Flyweight Pattern Abstract Factory Pattern Object Oriented Pattern Benefits of using design pattern Following are the different benefits of design pattern − Patterns provide developer a selection of tried and tested solutions for the specified problems. All design patterns are language neutral. Patterns help to achieve communication and maintain well documentation. It includes a record of accomplishment to reduce any technical risk to the project. Design patterns are highly flexible to use and easy to understand. Print Page Previous Next Advertisements ”;

Python Design Patterns – Builder

Python Design Patterns – Builder ”; Previous Next Builder Pattern is a unique design pattern which helps in building complex object using simple objects and uses an algorithmic approach. This design pattern comes under the category of creational pattern. In this design pattern, a builder class builds the final object in step-by-step procedure. This builder is independent of other objects. Advantages of Builder Pattern It provides clear separation and a unique layer between construction and representation of a specified object created by class. It provides better control over construction process of the pattern created. It gives the perfect scenario to change the internal representation of objects. How to implement builder pattern? In this section, we will learn how to implement the builder pattern. class Director: __builder = None def setBuilder(self, builder): self.__builder = builder def getCar(self): car = Car() # First goes the body body = self.__builder.getBody() car.setBody(body) # Then engine engine = self.__builder.getEngine() car.setEngine(engine) # And four wheels i = 0 while i < 4: wheel = self.__builder.getWheel() car.attachWheel(wheel) i += 1 return car # The whole product class Car: def __init__(self): self.__wheels = list() self.__engine = None self.__body = None def setBody(self, body): self.__body = body def attachWheel(self, wheel): self.__wheels.append(wheel) def setEngine(self, engine): self.__engine = engine def specification(self): print “body: %s” % self.__body.shape print “engine horsepower: %d” % self.__engine.horsepower print “tire size: %d”” % self.__wheels[0].size class Builder: def getWheel(self): pass def getEngine(self): pass def getBody(self): pass class JeepBuilder(Builder): def getWheel(self): wheel = Wheel() wheel.size = 22 return wheel def getEngine(self): engine = Engine() engine.horsepower = 400 return engine def getBody(self): body = Body() body.shape = “SUV” return body # Car parts class Wheel: size = None class Engine: horsepower = None class Body: shape = None def main(): jeepBuilder = JeepBuilder() # initializing the class director = Director() # Build Jeep print “Jeep” director.setBuilder(jeepBuilder) jeep = director.getCar() jeep.specification() print “” if __name__ == “__main__”: main() Output The above program generates the following output − Print Page Previous Next Advertisements ”;

Python Design Patterns – Prototype

Python Design Patterns – Prototype ”; Previous Next Prototype design pattern helps to hide the complexity of the instances created by the class. The concept of the existing object will differ with that of the new object, which is created from scratch. The newly copied object may have some changes in the properties if required. This approach saves time and resources that go in for the development of a product. How to implement a prototype pattern? Let us now see how to implement a prototype pattern. import copy class Prototype: _type = None _value = None def clone(self): pass def getType(self): return self._type def getValue(self): return self._value class Type1(Prototype): def __init__(self, number): self._type = “Type1” self._value = number def clone(self): return copy.copy(self) class Type2(Prototype): “”” Concrete prototype. “”” def __init__(self, number): self._type = “Type2” self._value = number def clone(self): return copy.copy(self) class ObjectFactory: “”” Manages prototypes. Static factory, that encapsulates prototype initialization and then allows instatiation of the classes from these prototypes. “”” __type1Value1 = None __type1Value2 = None __type2Value1 = None __type2Value2 = None @staticmethod def initialize(): ObjectFactory.__type1Value1 = Type1(1) ObjectFactory.__type1Value2 = Type1(2) ObjectFactory.__type2Value1 = Type2(1) ObjectFactory.__type2Value2 = Type2(2) @staticmethod def getType1Value1(): return ObjectFactory.__type1Value1.clone() @staticmethod def getType1Value2(): return ObjectFactory.__type1Value2.clone() @staticmethod def getType2Value1(): return ObjectFactory.__type2Value1.clone() @staticmethod def getType2Value2(): return ObjectFactory.__type2Value2.clone() def main(): ObjectFactory.initialize() instance = ObjectFactory.getType1Value1() print “%s: %s” % (instance.getType(), instance.getValue()) instance = ObjectFactory.getType1Value2() print “%s: %s” % (instance.getType(), instance.getValue()) instance = ObjectFactory.getType2Value1() print “%s: %s” % (instance.getType(), instance.getValue()) instance = ObjectFactory.getType2Value2() print “%s: %s” % (instance.getType(), instance.getValue()) if __name__ == “__main__”: main() Output The above program will generate the following output − The output helps in creating new objects with the existing ones and it is clearly visible in the output mentioned above. Print Page Previous Next Advertisements ”;