Click here to Skip to main content
15,881,516 members
Articles / Programming Languages / Python
Technical Blog

Facade Pattern

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
8 Jan 2013CPOL2 min read 17.8K   7   2
This is the first of actual posts in my series on design patterns in Python.

This is the first of actual posts in my series on design patterns in Python.

This will be about the Facade pattern which is a structural pattern.

The Purpose

The facade pattern is used to make one object with a simple interface represent a complicated system. The problem often occurs in programming where you have a series of interconnected classes where the functions must be called in a certain order or have complicated interdependencies.

This pattern is to give a standard interface to such a system, so you don’t have to rely on reading how you call the system in one of the files or look at example usage.

The Pattern

Here is a UML diagram representing the pattern.

UML for Facade pattern

UML is a very useful tool however I have not used a lot yet. It provides a (mostly) standardised way of representing system structure for object oriented programming. I intend to use a UML diagram to represent each pattern in this series, I will explain them so hopefully you don’t need to know UML to follow what’s going on.

This is a nice and simple UML diagram with the following elements; the facade box represents a class, the boxes in the subsystem box could be any object such as a class or a function and the lines between them indicate some relationship.

This shows that the pattern is just one class which groups together a lot of other objects and uses them in some way.

An Example Usage

Here is an implementation of this in python. For this example I am using a car. As this is a small example I will not create a whole complex sub-system, just a few classes.

Here are the three classes which make up the sub-system; Engine, StarterMotor and Battery.

#==============================================================================
class Engine(object):
    
    def __init__(self):
        # how much the motor is spinning in revs per minute
        self.spin = 0

    def start(self, spin):
        if (spin > 2000):
            self.spin = spin // 15

#==============================================================================
class StarterMotor(object):
    
    def __init__(self):
        # how much the starter motor is spinning in revs per minute
        self.spin = 0

    def start(self, charge):
        # if there is enough power then spin fast
        if (charge > 50):
            self.spin = 2500

#==============================================================================
class Battery(object):

    def __init__(self):
        # % charged, starts flat
        self.charge = 0

So now we need our facade object which will work as a common interface for the car.

#==============================================================================
class Car(object):
    # the facade object that deals with the battery, engine and starter motor.
    
    def __init__(self):
        self.battery = Battery()
        self.starter = StarterMotor()
        self.engine = Engine()
        
    def turn_key(self):
        # use the battery to turn the starter motor
        self.starter.start(self.battery.charge)

        # use the starter motor to spin the engine
        self.engine.start(self.starter.spin)
        
        # if the engine is spinning the car is started
        if (self.engine.spin > 0):
            print("Engine Started.")
        else:
            print("Engine Not Started.")

    def jump(self):
        self.battery.charge = 100
        print("Jumped")

This enables the user of Car to use the system as it was intended to be used. I include this at the bottom of the python module so that on running it makes a car, tries to start it, then jumps it to start it.

#==============================================================================
if (__name__ == "__main__"):
    corsa = Car()
    corsa.turn_key()
    corsa.jump()
    corsa.turn_key()

The output of this program is the following;

Engine Not Started.
Jumped
Engine Started.

That is a simple example of the facade design pattern. The code for this is on my GitHub here.

All of the code for this series can be found in this repository.


This article was originally posted at http://davidcorne.com/2013/01/07/facade-pattern

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
I am a C++ developer with a strong interest in Python, C#, and Qt. I work on a native C++ application which uses COM to call C# in order to use a WPF GUI.

While I develop an application using WPF exclusivly for windows, I am a big linux user. My favourite distro at the moment is Linux Mint, and I love the delights of the command line,.

If you've read something of mine and you enjoyed it, check out my blog.

I am also active on various other sites, listed below.

Coding Sites



  • BitBucket where I keep the majority of my projects.
  • GitHub where I have a few older projects. This includes my current long term project, I'm writing a book about design patterns in python. Find the repository here and blog posts about individual patterns here
  • Stackoverflow I'm not too active on stackoverflow, I'm more of a listener.
  • coderwall and coderbits two profile compilation websites.


Social Sites



Comments and Discussions

 
GeneralMy vote of 5 Pin
G Haranadh12-Feb-13 18:44
G Haranadh12-Feb-13 18:44 
GeneralRe: My vote of 5 Pin
David Corne12-Feb-13 21:18
David Corne12-Feb-13 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.