Python Design Patterns – Adapter

Python Design Patterns – Adapter ”; Previous Next Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class, which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be the case of a card reader, which acts as an adapter between memory card and a laptop. You plug in the memory card into the card reader and the card reader into the laptop so that memory card can be read via the laptop. The adapter design pattern helps to work classes together. It converts the interface of a class into another interface based on requirement. The pattern includes a speciation a polymorphism which names one name and multiple forms. Say for a shape class which can use as per the requirements gathered. There are two types of adapter pattern − Object Adapter Pattern This design pattern relies on object implementation. Hence, it is called the Object Adapter Pattern. Class Adapter Pattern This is an alternative way to implement the adapter design pattern. The pattern can be implemented using multiple inheritances. How to implement the adapter pattern? Let us now see how to implement the adapter pattern. class EuropeanSocketInterface: def voltage(self): pass def live(self): pass def neutral(self): pass def earth(self): pass # Adaptee class Socket(EuropeanSocketInterface): def voltage(self): return 230 def live(self): return 1 def neutral(self): return -1 def earth(self): return 0 # Target interface class USASocketInterface: def voltage(self): pass def live(self): pass def neutral(self): pass # The Adapter class Adapter(USASocketInterface): __socket = None def __init__(self, socket): self.__socket = socket def voltage(self): return 110 def live(self): return self.__socket.live() def neutral(self): return self.__socket.neutral() # Client class ElectricKettle: __power = None def __init__(self, power): self.__power = power def boil(self): if self.__power.voltage() > 110: print “Kettle on fire!” else: if self.__power.live() == 1 and self.__power.neutral() == -1: print “Coffee time!” else: print “No power.” def main(): # Plug in socket = Socket() adapter = Adapter(socket) kettle = ElectricKettle(adapter) # Make coffee kettle.boil() return 0 if __name__ == “__main__”: main() Output The above program generates the following output − Explanation The code includes adapter interface with various parameters and attributes. It includes Adaptee along with Target interface that implements all the attributes and displays the output as visible. Print Page Previous Next Advertisements ”;

Python Design Patterns – Gist

Python Design Patterns – Gist ”; Previous Next Python is an open source scripting language, which is high-level, interpreted, interactive and object-oriented. It is designed to be highly readable. The syntax of Python language is easy to understand and uses English keywords frequently. Features of Python Language In this section, we will learn about the different features of Python language. Interpreted Python is processed at runtime using the interpreter. There is no need to compile program before execution. It is similar to PERL and PHP. Object-Oriented Python follows object-oriented style and design patterns. It includes class definition with various features like encapsulation, polymorphism and many more. Portable Python code written in Windows operating system and can be used in Mac operating system. The code can be reused and portable as per the requirements. Easy to code Python syntax is easy to understand and code. Any developer can understand the syntax of Python within few hours. Python can be described as “programmer-friendly” Extensible If needed, a user can write some of Python code in C language as well. It is also possible to put python code in source code in different languages like C++. This makes Python an extensible language. Important Points Consider the following important points related to Python programming language − It includes functional and structured programming methods as well as object-oriented programming methods. It can be used as scripting language or as a programming language. It includes automatic garbage collection. It includes high-level dynamic data types and supports various dynamic type checking. Python includes a feature of integration with C, C++ and languages like Java. How to download python language in your system? To download Python language in your system, follow this link − https://www.python.org/downloads/ It includes packages for various operating systems like Windows, MacOS and Linux distributions. The Important Tools in Python In this section, we will learn in brief about a few important tools in Python. Python Strings The basic declaration of strings is as follows − str = ”Hello World!” Python Lists The lists of python can be declared as compound data types separated by commas and enclosed within square brackets ([]). list = [ ”abcd”, 786 , 2.23, ”john”, 70.2 ] tinylist = [123, ”john”] Python Tuples A tuple is dynamic data type of Python, which consists of number of values separated by commas. Tuples are enclosed with parentheses. tinytuple = (123, ”john”) Python Dictionary Python dictionary is a type of hash table. A dictionary key can be almost any data type of Python. The data types are usually numbers or strings. tinydict = {”name”: ”omkar”,”code”:6734, ”dept”: ”sales”} What constitutes a design pattern in Python? Python helps in constituting a design pattern using the following parameters − Pattern Name Intent Aliases Motivation Problem Solution Structure Participants Constraints Sample Code Print Page Previous Next Advertisements ”;

Python Design Patterns – Facade

Python Design Patterns – Facade ”; Previous Next Facade design pattern provides a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that any subsystem can use. A facade class knows which subsystem is responsible for a request. How to design a facade pattern? Let us now see how to design a facade pattern. class _IgnitionSystem(object): @staticmethod def produce_spark(): return True class _Engine(object): def __init__(self): self.revs_per_minute = 0 def turnon(self): self.revs_per_minute = 2000 def turnoff(self): self.revs_per_minute = 0 class _FuelTank(object): def __init__(self, level=30): self._level = level @property def level(self): return self._level @level.setter def level(self, level): self._level = level class _DashBoardLight(object): def __init__(self, is_on=False): self._is_on = is_on def __str__(self): return self.__class__.__name__ @property def is_on(self): return self._is_on @is_on.setter def is_on(self, status): self._is_on = status def status_check(self): if self._is_on: print(“{}: ON”.format(str(self))) else: print(“{}: OFF”.format(str(self))) class _HandBrakeLight(_DashBoardLight): pass class _FogLampLight(_DashBoardLight): pass class _Dashboard(object): def __init__(self): self.lights = {“handbreak”: _HandBrakeLight(), “fog”: _FogLampLight()} def show(self): for light in self.lights.values(): light.status_check() # Facade class Car(object): def __init__(self): self.ignition_system = _IgnitionSystem() self.engine = _Engine() self.fuel_tank = _FuelTank() self.dashboard = _Dashboard() @property def km_per_litre(self): return 17.0 def consume_fuel(self, km): litres = min(self.fuel_tank.level, km / self.km_per_litre) self.fuel_tank.level -= litres def start(self): print(“nStarting…”) self.dashboard.show() if self.ignition_system.produce_spark(): self.engine.turnon() else: print(“Can”t start. Faulty ignition system”) def has_enough_fuel(self, km, km_per_litre): litres_needed = km / km_per_litre if self.fuel_tank.level > litres_needed: return True else: return False def drive(self, km = 100): print(“n”) if self.engine.revs_per_minute > 0: while self.has_enough_fuel(km, self.km_per_litre): self.consume_fuel(km) print(“Drove {}km”.format(km)) print(“{:.2f}l of fuel still left”.format(self.fuel_tank.level)) else: print(“Can”t drive. The Engine is turned off!”) def park(self): print(“nParking…”) self.dashboard.lights[“handbreak”].is_on = True self.dashboard.show() self.engine.turnoff() def switch_fog_lights(self, status): print(“nSwitching {} fog lights…”.format(status)) boolean = True if status == “ON” else False self.dashboard.lights[“fog”].is_on = boolean self.dashboard.show() def fill_up_tank(self): print(“nFuel tank filled up!”) self.fuel_tank.level = 100 # the main function is the Client def main(): car = Car() car.start() car.drive() car.switch_fog_lights(“ON”) car.switch_fog_lights(“OFF”) car.park() car.fill_up_tank() car.drive() car.start() car.drive() if __name__ == “__main__”: main() Output The above program generates the following output − Explanation This program is designed with a scenario. It is that of starting the engine of a car or any driving vehicle. If you observe the code, it includes the associated functions to drive, to park and to consume fuel as well. 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 ”;