working on it ...


Explore Public Snippets

Sort by

Found 1,272 snippets matching: patterns

    public by mprisznyak modified Apr 15, 2014  229386  0  6  3


    a tongue-in-cheek example for the observer pattern
    # -*- coding: utf-8 -*-
    a tongue-in-cheek example for the observer pattern
    Hungary elects today :)
    # let's use a decorator
    def observe(f):
        def decorated(self, something):
            for obs in self.observers:
                obs.notify(self, f.func_name, something)
            return f(self, something)
        return decorated
    class Observer(object):
        def __init__(self, name):
   = name
        def notify(self, observed, action, something):
            name =
            observed_name =
            print "{name} reports that {observed_name} {action} {something}".format(**locals())
    class Voter(object):
        def __init__(self, name):
   = name
            self.observers = []
        def add_observers(self, *observers):
        def votes(self, party):
            print "{name} votes for {party}".format(, party=party)
        def eats(self, food):
            print "{name} eats {food}".format(, food=food)
        def digests(self, food):
            print "{name} digests {food}".format(, food=food)
    if __name__ == "__main__":
        # observers
        OSCE = Observer("Organization for Security and Co-operation in Europe")
        UNO  = Observer("United Nations")
        God  = Observer("God")
        # poor voter
        jani = Voter("Kovács János")
        jani.add_observers(OSCE, UNO, God)
        jani.eats("Sunday lunch")
        # luckily digestion is not observed
        jani.digests("Sunday lunch")

    public by SamHall modified Jan 22, 2014  5889  24  7  1

    Amazing - Pure CSS Background Patterns Enjoy !!

    These patterns are simply beautiful, I will give credit back to the author as soon as I find the Link, but be rest assured they do have a full royalty free use license for both commercial and non commercial use
    radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 9%, hsla(0, 100%, 20%, 0) 9%) 0 0,
    radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 8%, hsla(0, 100%, 20%, 0) 10%) 50px 50px,
    radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 50px 0,
    radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 0 50px,
    radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 50px 0,
    radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 100px 50px,
    radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 0 0,
    radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 50px 50px,
    linear-gradient(45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0,
    linear-gradient(-45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0;
    background-color: #300;
    background-size: 100px 100px;
    \* Name says it all on this one *\
    starrynight {
    radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 40px),
    radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 30px),
    radial-gradient(white, rgba(255,255,255,.1) 2px, transparent 40px),
    radial-gradient(rgba(255,255,255,.4), rgba(255,255,255,.1) 2px, transparent 30px);
    background-size: 550px 550px, 350px 350px, 250px 250px, 150px 150px;
    background-position: 0 0, 40px 60px, 130px 270px, 70px 100px;
    \* dark grey with the small dotted holes in a tight pattern well done *\
    CarbomFiber {
    radial-gradient(black 15%, transparent 16%) 0 0,
    radial-gradient(black 15%, transparent 16%) 8px 8px,
    radial-gradient(rgba(255,255,255,.1) 15%, transparent 20%) 0 1px,
    radial-gradient(rgba(255,255,255,.1) 15%, transparent 20%) 8px 9px;
    background-size:16px 16px;
    \* Two shades of gray *\
    Carbon {
    linear-gradient(27deg, #151515 5px, transparent 5px) 0 5px,
    linear-gradient(207deg, #151515 5px, transparent 5px) 10px 0px,
    linear-gradient(27deg, #222 5px, transparent 5px) 0px 10px,
    linear-gradient(207deg, #222 5px, transparent 5px) 10px 5px,
    linear-gradient(90deg, #1b1b1b 10px, transparent 10px),
    linear-gradient(#1d1d1d 25%, #1a1a1a 25%, #1a1a1a 50%, transparent 50%, transparent 75%, #242424 75%, #242424);
    background-color: #131313;
    background-size: 20px 20px;
    \* clean well done notebook paper-narrow ruled *\
    lined Paper {  
    background-color: #fff;
    linear-gradient(90deg, transparent 79px, #abced4 79px, #abced4 81px, transparent 81px),
    linear-gradient(#eee .1em, transparent .1em);
    background-size: 100% 1.2em;

    public by mprisznyak modified Jun 14, 2014  3847  0  6  12


    a tongue-in-cheek example for the adapter pattern
    demonstrate the adapter pattern
    looking up adapters in a registry is also demonstrated
    You really want a Lion because some roaring is needed however your Cat can meow only.
    For animal rights reasons, you cannot change your Cat directly but a Cat2Lion adapter will still do the job.
    class SexError(Exception):
        def __str__(self):
            return "Sorry, try Eurovision instead. All our felines are either males or females."
    class Feline(object):
        cats and lions are felines
        def __init__(self, name, sex="male"):
   = name
            if sex in ["male", "female"]:
        = sex
                raise SexError()
        def groom(self):
            sex2pronoun = {"male": ["he", "him"], "female": ["she", "her"]}
            nominative, objective = sex2pronoun[]        
            print "{name} licks {objective_pronoun}self and {nominative_pronoun} is going to be very well-groomed!".format(
                    name =,
                    objective_pronoun = objective,
                    nominative_pronoun = nominative,
    #  these are protected animals you cannot alter
    class Cat(Feline):
        def meow(self):
            return "Meow, meow!"
    class Lion(Feline):
        def roar(self):
            return "Roar, roar!"
    class Adapter(object):
        a generic object adapter you should derive your own adapters from
        def __init__(self, adaptee):
            self.adaptee = adaptee
        def __getattr__(self, item):
            # delegate attributes
            return getattr(self.adaptee, item)
    class AdapterRegistry(object):
        a singleton which registers adapters and 
        provides an adapter factory method called 'adapt'
        adapters = {}
        def register(klass, from_, to_, adapter):
            klass.adapters[(from_, to_)] = adapter
        def adapt(klass, from_object, to_class):
                from_class = from_object.__class__
                adapter = klass.adapters[(from_class, to_class)]
                return adapter(from_object)
            except KeyError:
                raise Exception("it's impossible to turn a {from_name} into a {to_name}".format(
                            from_name = from_class.__name__),
                            to_name   = to_class.__name__
    # no cat is harmed during this alteration
    class Cat2Lion(Adapter):
         make a kitty roar
        def grooms(self):
        def roar(self):
            print "{name}, the cat says:".format(,
            return self._convert_voice(self.adaptee.meow())
        def _convert_voice(self, voice):
            voice = voice.lower()
            voice = voice.replace("meow", "roar")
            voice = voice.capitalize()
            return voice
    if __name__ == "__main__":
        mici = Cat("Mici", "female")
        AdapterRegistry.register(Cat, Lion, Cat2Lion) # cats may be turned into lions
        pocket_lion = AdapterRegistry.adapt(mici, Lion)
        # in fact pocket_lion, an adapted 'mici' object, is a Cat2Lion but she does behave like a Lion
        print, "is a", pocket_lion.__class__.__name__
        pocket_lion.grooms()  # lions can groom themselves
        print pocket_lion.roar()  # and now Mici, the kitty can roar, too!
        print "*"*80
        mici.groom() # cats can groom themselves
        mici.roar()  # cats just cannot roar properly...

    public by mprisznyak modified May 3, 2016  4825  2  5  4

    Command pattern

    Look ma, no objects!
    # Command Pattern 
    # using only functions which are "first-class citizen" in Python
    # and therefore they can be passed around 
    # do something actually
    def say(msg):
    # action functions
    def meauw():
    def woof():
    def neigh():
    # command -> action mapping
    actions =  {
    	"cat": meauw,
    	"dog": woof,
    	"horse": neigh,
    def handle(command):
      the command executioner...
      whoohaahaa! :)
    	action = actions.get(command,None)
    	if action: # existing command
    		action() # execute command
    	else: # no command found
    		say("Sorry! No %s here." % command) # no such command!
    for cmd in ["cat", "horse", "dog", "elephant"]:

    public by mprisznyak modified Aug 31, 2013  3690  17  6  2


    A design pattern which extends the singleton pattern to a map of named singleton instances. The construction of instances (cls() ) is not generic.
    def multiton(cls):
        instances = {}
        def get_instance(name):
            if name not in instances:
                instances[name] = cls()
            return instances[name]
        return get_instance
    class MyClass:
    assert a is b 
    assert not(a is c)

    public by mprisznyak modified Aug 4, 2015  3997  4  6  2

    Command design pattern

    A generic implementation for the Command design pattern It's demonstrated by two toy examples: 1/ a lamp which can be turned on and off 2/ a car which can be started up, filled up with petrol and driven. Some commands have parameters in this example.
    # -*- coding: utf-8 -*-
    Command design pattern
    class Command(object):
        """ generic command class
        def __init__(self, action, target):
            if callable(action):
                self._action = action
                raise Exception("callable action required")
   = target
        def execute(self, *args):
    class CommandClient(object):
        """Generic command client class"""
        def __init__(self, subject):
            self.subject = subject
            self._commands = {}
        def reset_subject(self):
        def add_command(self, command_name, action):
            :param command_name: the name of the command
            :type command_name: string
            :param action: a method of 'subject'
            :type action: string
            command_name = command_name.strip().upper()
            action = getattr(self.subject, action, None)
            if action:
                self._commands[command_name] = Command(action, self.subject)
                raise Exception("invalid action %s" % action)
        def execute(self, cmd, *args):
            :param cmd: command name
            :type cmd: string
            :param args: possible arguments for command
            :type args: optional input parameters for command
            cmd = cmd.strip().upper()
            command = self._commands.get(cmd)
            if command is None:
                print 'Unknown command ', cmd
        def query(self, attr):
            :param attr: name of attribute for 'subject'
            :type attr: string
            return getattr(self.subject, attr, "Undefined")
    class Light(object):
        """An example command receiver class"""
        ON = "ON"
        OFF = "OFF"
        def __init__(self):
            self.state = Light.OFF
        def turn_on(self):
            print "Switching the lights on"
            self.state = Light.ON
        def turn_off(self):
            print "Switching the lights off"
            self.state = Light.OFF
    class Car(object):
        """Another example command receiver class"""
        PETROL_IN_100 = 6.5
        def __init__(self):
            self.engine_running = False
            self.speed = 0.0
            self.fuel = 0.0
        def start(self):
            if self.fuel > 0.0:
                print "The car engine is starting..."
                self.engine_running = True
                print "The car tank is empty"
        def drive(self, distance):
            " drive distance kilometres"
            if self.engine_running:
                fuel_required = distance*self.PETROL_IN_100/100.0
                if self.fuel < fuel_required:
                    print "The car needs fuel"
                    print "  travelled %s kms" % distance
                    self.fuel -= fuel_required
                    print "  %s litres of petrol left" % self.fuel
                print "Car engine hasn't been started..."
        def fill_up_with_petrol(self, amount):
            self.fuel += amount
    if __name__ == "__main__":
        print "========= Lights ==========="
        light_switch = CommandClient(Light())
        light_switch.add_command("ON", "turn_on")
        light_switch.add_command("OFF", "turn_off")
        print "The lamp is", light_switch.query("state")
        print "The lamp is", light_switch.query("state")
        print "Invalid Command for lights"
        print "Lamp is", light_switch.query("state")
        print "====== Fine ride ========"
        car_ride = CommandClient(Car())
        car_ride.add_command("fill", "fill_up_with_petrol")
        car_ride.add_command("Start", "start")
        car_ride.add_command("DRIVE", "drive")
        car_ride.execute("FILL", 15)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 34)
        print "==== Fool's ride  ======="
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 77)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("FILL", 15)
        car_ride.execute("DRIVE", 18843)
        print "fuel: ", car_ride.query("fuel")            

    public by mprisznyak modified Sep 4, 2013  4014  2  6  2


    a toy example for the builder design pattern
      a toy example for the builder pattern
      in fact the builder is a more complicated factory pattern where business rules may be applied to build potentially complex data structures
    class Wheels(object):
        def __init__(self, diameter):
            self.diameter = diameter
        def make(self):
            r = self.__class__.__name__
            r = r.replace("_", " ")
            return r.lower()
    class Alloy_Wheels(Wheels):
    class Car(object):
        """A car can have GPS, trip computer and a various number of seaters. 
        Can be a city car, a sport car or a cabriolet."""
        CITY = "city car"
        SPORT = "sport car"
        CABRIOLET = "cabriolet car"
        def __init__(self, seats, wheels, GPS=False, trip_computer=False, make=CITY):
            self.seats = seats
            self.wheels = wheels
            self.GPS = GPS
            self.trip_computer = trip_computer
            self.make = make
        def __str__(self):
            if self.seats > 1:
                s = "This {self.make} has {self.seats} seats".format(self=self)
                s = "This car has {self.seats} seat".format(self=self)
            if self.GPS:
                s += ", it's got a GPS"
                s += ", it doesn't have a GPS"
            if self.trip_computer:
                s += "and it's got a trip computer. "
                s += "and it doesn't have a trip computer. "
            s += "The {0} are {1} cms in diameter.".format(self.wheels.make, self.wheels.diameter)
            return s
    class FaultyCarException(Exception):
        business rule violation!
    class CarBuilder(object):
            the builder which assembles the object
        def __init__(self):
            self.assembled_car = Car(2, Wheels(42))   # default car
        def seats(self):
            # return the number of seaters the car may have.
            return self.assembled_car.seats
        def seats(self, seats):
            # set the number of seaters the car may have.
            if seats != int(seats) or seats <= 0:
                raise FaultyCarException("the car must have one or more seats")
            self.assembled_car.seats = seats
        def wheels(self):
            return self.assembled_car.wheels.make, self.assembled_car.diameter
        def wheels(self, (wheel_type, diameter)):
            if wheel_type is Alloy_Wheels and self.assembled_car.make == Car.CITY:
                raise FaultyCarException("sorry, you cannot have alloy wheels for city cars")
            wheels = wheel_type(diameter)
            self.assembled_car.wheels = wheels
        def city_car(self):
            return self.assembled_car.make == Car.CITY
        def city_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.CITY
        def cabriolet_car(self):
            return self.assembled_car.make == Car.CABRIOLET
        def cabriolet_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.CABRIOLET
        def sport_car(self):
            return self.assembled_car.make == Car.SPORT
        def sport_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.SPORT
        def trip_computer(self):
            return self.assembled_car.trip_computer
        def trip_computer(self, choice):
            self.assembled_car.trip_computer = choice
        def GPS(self):
            return self.assembled_car.GPS
        def GPS(self, choice):
            self.assembled_car.GPS = choice
    if __name__ == "__main__":
        car_builder = CarBuilder()
        car_builder.seats = 2
        car_builder.cabriolet_car = True
        car_builder.trip_computer = True
        car_builder.GPS = False
        car_builder.wheels = Alloy_Wheels, 47
        print "Your car has been assembled! "
        print car_builder.assembled_car

    public by mprisznyak modified Apr 5, 2014  3052  2  6  3

    Hybrid publish-subscribe messaging

    a toy example with media publishers, media channels and viewers
    A somewhat non-trivial toy example for the publish-subscribe messaging pattern
    It demonstrates  hybrid message filtering which combines a topic-based approach  with a content-based one
    Message production and publication are decoupled.
    MediaPublishers create Programmes for Channels and the publish these there.
    Customers subscribe for programmes they are interested in but the Channels 
    also enforce age limit restrictions on these subscribers when they notify them.
    from random import choice, randint
    class Topics(object):
        enumerate programme topics
        SCIFI = "sci-fi films"
        ACTION = "action films"
        FAMILY = "family films"
        ROMANCE = "romantic films and soap operas"
        CARTOON = "cartoons"
        FOOTBALL = "football programmes"
        def all_topics(klass):
            return [getattr(klass, attr) for attr  in klass.__dict__ if attr == attr.upper()]
    class Programme(object):
        these are messages produced by MediaPublishers and received by Customers from Channels
        def __init__(self, topic, description, age_limit, publisher_name):
            self.topic = topic
            self.description = description
            self.age_limit = age_limit
            self.publisher_name = publisher_name
        def __str__(self):
            return """
            Topic: {self.topic}
            Age limit: {self.age_limit}
            produced by {self.publisher_name}
    class Channel(object):
        mediator objects where messages are published by MediaPublishers 
        and where Customers subscribe for notification
        def __init__(self, name):
   = name
            self.programmes = []
            self.customers = []
        def schedule(self, programme):
        def subscribe(self, customer):
            #print "{customer_name} has subscribed to channel {channel_name}".format(,
        def notify_consumers(self):
            notify all interested subscribers provided they are allowed to watch the programme
            for customer in self.customers:        # iterate  over subscribers
                for programme in self.programmes:  # iterate through received messages, that is programmes
                    topic = programme.topic
                    age_limit = programme.age_limit
                    if topic in customer.interests:  # topic-based filtering
                        if age_limit > customer.age: # content-based filtering
                            print "{customer_name} cannot watch {programme.description}".format(, programme=programme)
                        print "    on channel '{name}'\n".format(
    class MediaPublisher(object):
        message publisher
        def __init__(self, name):
   = name
        def get_programme(self, topic ):
            builder method for Programmes
            descriptions = {Topics.CARTOON: ["Tom and Jerry", "The Flintstones"],
                           Topics.FOOTBALL: ["the Champions Leage final", "a boring football match", "the World Cup semifinal"],
                           Topics.ACTION:  ["The Terminator", "Rambo XVIII", "Robocop", "Die hard 8"],
                           Topics.FAMILY:  ["Santa Clause gone mad", "Fishing on the lake", "The return of Easter Bunny"],
                           Topics.ROMANCE: ["Antonio and Cleopatra", "Love till you drop dead", "Never-ending love story"],
                           Topics.SCIFI: ["Star Wars XXVII", "Star Trek", "Andromeda", "Babylon 9"],
            description = choice(descriptions[topic])
            if topic in (Topics.CARTOON, Topics.FOOTBALL, Topics.FAMILY): # kids safe
                age_limit = 0
                if randint(1,3) == 3:
                    age_limit = 0
                    age_limit = 14
            return Programme(topic, description, age_limit, )
        def provide(self, channel, topic):
            MediaPublisher sends a programme to Channel in this topic
            programme = self.get_programme(topic)
    class Customer(object):
        message subscriber
        def __init__(self, name, age):
   = name
            self.age = age
            self.interests = []
        def add_interest(self, interest):
        def subscribe(self, channel):
        def watch(self, programme):
            print "{name} is going to watch a {programme.description} made by {programme.publisher_name}".format(,
        def __str__(self):
            return """
            Customer records:
                name : {}
                age  : {self.age}
                interests: {self.interests}
    if __name__ == "__main__":
        # initialize system
        john = Customer("John Doe", 45)
        mary = Customer("Mary Popkins", 54)
        pete = Customer("Pete Little", 9)
        funcaster = Channel("The Funstatic Caster")
        kill_your_time = Channel("Kill All Your Time with US")
        public_services = Channel("Taxpayer paid")
        channels = [funcaster, kill_your_time, public_services]
        # subscriptions
        doozney_productions = MediaPublisher("Doozney Inc")
        lion_studio   = MediaPublisher("Lions and Lambs Studio")
        def cast_dice():
            return randint(1,6)
        # decide on broadcasting
        for topic in Topics.all_topics():
            if cast_dice() <= 3:
                doozney_productions.provide(public_services, topic)
                doozney_productions.provide(funcaster, topic)
                doozney_productions.provide(kill_your_time, topic)
            if cast_dice() >= 5:
                lion_studio.provide(public_services, topic)
                lion_studio.provide(kill_your_time, topic)
                lion_studio.provide(funcaster, topic)
        for channel in channels:

    public by mprisznyak modified May 1, 2014  2325  2  6  4

    Chain of responsibility

    a tongue-in-cheek example for the chain of responsibility pattern
    The chain of responsibility pattern aims at minimizing the coupling  between request senders and request receivers.
    The patter provides  more than one object a chance to handle the request. The request travels along the chain until an object is found which can handle it.
    class Handler(object):
        def __init__(self, next_handler):
            self.next_handler = next_handler
        def name(self):
            klass_name = self.__class__.__name__
            return klass_name.lower()
        def handle(self, request):
                handler = getattr(self, request)
            except AttributeError as e:
                # pass on request
                print "   passing request '{request}' from {from_} to {name}".format(request=request,,
    class Boss(Handler):
        def __init__(self, employee):
            super(Boss, self).__init__(employee)
        def shout(self):
            print "Hey!!"
    class Employee(Handler):
        def __init__(self, wife):
            super(Employee, self).__init__(wife)
        def quarrel(self):
            print "you're so nasty, darling!"
    class Wife(Handler):
        def __init__(self, kid):
            super(Wife, self).__init__(kid)
        def tell_off_kid(self):
            print "{name} says to {next_in_chain}... 'you're a bad boy!' ".format(,
    class Kid(Handler):
        def __init__(self, dog):
            super(Kid, self).__init__(dog)
        def kick_the_dog(self):
            print "The dog is kicked... and says",
    class Dog(object):
        def __init__(self):
   = "Rex"
        def handle(self, anything):
        def woof(self):
            print "woof!"
    if __name__ == '__main__':
        # let's build the chain
        pete = Kid(Dog())
        mary = Wife(pete)
        john = Employee(mary)
        pmb  = Boss(john)
        # boss shouts like mad
        # kid will be told off
        # dog will be kicked
        # employee will argue with wife
        # employee cannot tell wife off so poor dog will bark
        # employee cannot shout... poor dog will bark

    public by mprisznyak modified Aug 31, 2013  2949  1  6  1


    A toy example for the factory design pattern
      a toy example for the factory pattern
    class Car(object):
        """A car can have GPS, trip computer and a various number of seaters. 
        Can be a city car, a sport car or a cabriolet."""
        CITY = "city car"
        SPORT = "sport car"
        CABRIOLET = "cabriolet car"
        def __init__(self, seats, GPS=False, trip_computer=False, make=CITY):
            self.seats = seats
            self.GPS = GPS
            self.trip_computer = trip_computer
            self.make = make
        def __str__(self):
            if self.seats > 1:
                s = "This {self.make} has {self.seats} seats".format(self=self)
                s = "This car has {self.seats} seat".format(self=self)
            if self.GPS:
                s += ", it's got a GPS"
                s += ", it doesn't have a GPS"
            if self.trip_computer:
                s += "and it's got a trip computer. "
                s += "and it doesn't have a trip computer. "
            return s
    class CarFactory(object):
        def make_normal_city_car(self):
            return Car(4)
        def make_normal_city_car_in_Hungary(self):
            # return patched object
            hungarian_car = self.make_normal_city_car()
            hungarian_car.made_in = "Hungary"
            return hungarian_car
        def make_luxury_city_car(self):
            return Car(4, True, True)
        def make_normal_cabriolet_car(self):
            return Car(2, make=Car.CABRIOLET)
        def make_luxury_cabriolet_car(self):
            return Car(2, True, True, Car.CABRIOLET)
    if __name__ == "__main__":
        print CarFactory.make_normal_city_car_in_Hungary()
        print CarFactory.make_luxury_cabriolet_car()
    • Public Snippets
    • Channels Snippets