working on it ...

Filters

Explore Public Snippets

Sort by

Found 1,087 snippets matching: patterns

    public by SamHall modified Jan 22, 2014  2608  70  6  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
    
    \* BURGANDY RED LEATHER W/ THE DEEP BUTTONED DOWN PILLOWED DIAMOND TUCK *\
    
    uphoulstry{
    background:
    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 {
    background-color:black;
    background-image:
    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 {
    
    background:
    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-color:#282828;
    background-size:16px 16px;
    
    }
    
    \* Two shades of gray *\
    
    Carbon {
    background:
    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;
    background-image:
    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  902  0  6  11

    Adapter

    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"):
            self.name = name
            if sex in ["male", "female"]:
                self.sex  = sex
            else:
                raise SexError()
    
        def groom(self):
            sex2pronoun = {"male": ["he", "him"], "female": ["she", "her"]}
            nominative, objective = sex2pronoun[self.sex]        
            print "{name} licks {objective_pronoun}self and {nominative_pronoun} is going to be very well-groomed!".format(
                    name = self.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 = {}
    
        @classmethod
        def register(klass, from_, to_, adapter):
            klass.adapters[(from_, to_)] = adapter
    
        @classmethod
        def adapt(klass, from_object, to_class):
            try:
                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):
            self.adaptee.grooms()
    
        def roar(self):
            print "{name}, the cat says:".format(name=self.adaptee.name),
            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 pocket_lion.name, "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 Aug 4, 2015  1509  5  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
            else:
                raise Exception("callable action required")
            self.target = target
    
        def execute(self, *args):
            self._action(*args)
    
    
    class CommandClient(object):
        """Generic command client class"""
    
        def __init__(self, subject):
            self.subject = subject
            self._commands = {}
    
        def reset_subject(self):
            self.subject.__init__()
    
        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)
            else:
                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
            else:
                command.execute(*args)
    
        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
            else:
                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"
                else:
                    print "  travelled %s kms" % distance
                    self.fuel -= fuel_required
                    print "  %s litres of petrol left" % self.fuel
            else:
                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")
    
        light_switch.execute("ON")
        print "The lamp is", light_switch.query("state")
        light_switch.execute("OFF")
        print "The lamp is", light_switch.query("state")
        print "Invalid Command for lights"
        light_switch.execute("****")
        print "Lamp is", light_switch.query("state")
    
    
        print
        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("START")
        car_ride.execute("DRIVE", 34)
    
        print
        print "==== Fool's ride  ======="
        car_ride.reset_subject()
    
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 77)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("START")
        car_ride.execute("FILL", 15)
        car_ride.execute("DRIVE", 18843)
        print "fuel: ", car_ride.query("fuel")            

    public by mprisznyak modified Aug 31, 2013  912  10  5  2

    Multiton

    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
     
    @multiton
    class MyClass:
    	pass
    
    a=MyClass("type0")
    b=MyClass("type0")
    c=MyClass("type1")
    
    assert a is b 
    assert not(a is c)

    public by mprisznyak modified May 1, 2014  595  1  5  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
    
        @property
        def name(self):
            klass_name = self.__class__.__name__
            return klass_name.lower()
    
        def handle(self, request):
            try:
                handler = getattr(self, request)
                handler()
            except AttributeError as e:
                # pass on request
                print "   passing request '{request}' from {from_} to {name}".format(request=request, from_=self.name,
                                                                                  name= self.next_handler.name)
                self.next_handler.handle(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(name=self.name,
                                                                                  next_in_chain=self.next_handler.name)
    
    class Kid(Handler):
    
        def __init__(self, dog):
            super(Kid, self).__init__(dog)
    
        def kick_the_dog(self):
            print "The dog is kicked... and says",
            self.next_handler.handle("kick")
    
    class Dog(object):
    
        def __init__(self):
            self.name = "Rex"
    
        def handle(self, anything):
            self.woof()
    
        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
        pmb.handle("shout")
        # kid will be told off
        pmb.handle("tell_off_kid")
        # dog will be kicked
        pmb.handle("kick_the_dog")
        # employee will argue with wife
        john.handle("quarrel")
        # employee cannot tell wife off so poor dog will bark
        john.handle("tell_off")
        # employee cannot shout... poor dog will bark
        john.handle("shout")

    public by mprisznyak modified Apr 5, 2014  652  2  5  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"
    
        @classmethod
        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}
    
            {self.description}
    
            Age limit: {self.age_limit}
            produced by {self.publisher_name}
    
            """.format(self=self)
    
    class Channel(object):
        """
        mediator objects where messages are published by MediaPublishers 
        and where Customers subscribe for notification
        """
        def __init__(self, name):
            self.name = name
            self.programmes = []
            self.customers = []
    
        def schedule(self, programme):
            self.programmes.append(programme)
    
        def subscribe(self, customer):
            #print "{customer_name} has subscribed to channel {channel_name}".format(customer_name=customer.name,
            #                                                                       channel_name=self.name)
            self.customers.append(customer)
    
        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(customer_name=customer.name, programme=programme)
                        else:
                            customer.watch(programme)
                        print "    on channel '{name}'\n".format(name=self.name)
    
    
    
    class MediaPublisher(object):
        """
        message publisher
        """
    
        def __init__(self, name):
            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
            else:
                if randint(1,3) == 3:
                    age_limit = 0
                else:
                    age_limit = 14
    
            return Programme(topic, description, age_limit, self.name )
    
        def provide(self, channel, topic):
            """
            MediaPublisher sends a programme to Channel in this topic
            """
            programme = self.get_programme(topic)
            channel.schedule(programme)
    
    
    class Customer(object):
        """
        message subscriber
        """
        def __init__(self, name, age):
            self.name = name
            self.age = age
            self.interests = []
    
        def add_interest(self, interest):
            self.interests.append(interest)
    
        def subscribe(self, channel):
            channel.subscribe(self)
    
        def watch(self, programme):
            print "{name} is going to watch a {programme.description} made by {programme.publisher_name}".format(name=self.name,
                                                                                                                 programme=programme)
    
        def __str__(self):
            return """
            Customer records:
                name : {self.name}
                age  : {self.age}
                interests: {self.interests}
            """.format(self=self)
    
    
    
    if __name__ == "__main__":
    
        # initialize system
    
        john = Customer("John Doe", 45)
        john.add_interest(Topics.SCIFI)
        john.add_interest(Topics.ACTION)
        john.add_interest(Topics.FOOTBALL)
    
        mary = Customer("Mary Popkins", 54)
        mary.add_interest(Topics.ROMANCE)
        mary.add_interest(Topics.FAMILY)
    
        pete = Customer("Pete Little", 9)
        pete.add_interest(Topics.CARTOON)
        pete.add_interest(Topics.FOOTBALL)
        pete.add_interest(Topics.ACTION)
        pete.add_interest(Topics.FAMILY)
    
        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
        john.subscribe(funcaster)
        john.subscribe(kill_your_time)
        john.subscribe(public_services)
    
        mary.subscribe(funcaster)
        mary.subscribe(public_services)
    
        pete.subscribe(funcaster)
        pete.subscribe(kill_your_time)
    
    
        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)
            else:
                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)
            else:
                lion_studio.provide(funcaster, topic)
    
        for channel in channels:
            channel.notify_consumers()
    

    public by mprisznyak modified Sep 4, 2013  834  2  5  2

    Builder

    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
    
        @property
        def make(self):
            r = self.__class__.__name__
            r = r.replace("_", " ")
            return r.lower()
    
    
    class Alloy_Wheels(Wheels):
        pass
    
    
    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)
            else:
                s = "This car has {self.seats} seat".format(self=self)
            if self.GPS:
                s += ", it's got a GPS"
            else:
                s += ", it doesn't have a GPS"
            if self.trip_computer:
                s += "and it's got a trip computer. "
            else:
                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!
        """
        pass
    
    
    class CarBuilder(object):
        """
            the builder which assembles the object
        """
        def __init__(self):
            self.assembled_car = Car(2, Wheels(42))   # default car
    
        @property
        def seats(self):
            # return the number of seaters the car may have.
            return self.assembled_car.seats
    
        @seats.setter
        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
    
        @property
        def wheels(self):
            return self.assembled_car.wheels.make, self.assembled_car.diameter
    
        @wheels.setter
        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
    
    
        @property
        def city_car(self):
            return self.assembled_car.make == Car.CITY
    
        @city_car.setter
        def city_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.CITY
    
        @property
        def cabriolet_car(self):
            return self.assembled_car.make == Car.CABRIOLET
    
        @cabriolet_car.setter
        def cabriolet_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.CABRIOLET
    
        @property
        def sport_car(self):
            return self.assembled_car.make == Car.SPORT
    
        @sport_car.setter
        def sport_car(self, choice):
            if choice == True:
                self.assembled_car.make = Car.SPORT
    
        @property
        def trip_computer(self):
            return self.assembled_car.trip_computer
    
        @trip_computer.setter
        def trip_computer(self, choice):
            self.assembled_car.trip_computer = choice
    
        @property
        def GPS(self):
            return self.assembled_car.GPS
    
        @GPS.setter
        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 15, 2014  677  0  5  3

    Observer

    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):
            self.name = name
    
        def notify(self, observed, action, something):
            name = self.name
            observed_name = observed.name
            print "{name} reports that {observed_name} {action} {something}".format(**locals())
    
    
    class Voter(object):
    
        def __init__(self, name):
            self.name = name
            self.observers = []
    
        def add_observers(self, *observers):
            self.observers.extend(observers)
    
        @observe
        def votes(self, party):
            print "{name} votes for {party}".format(name=self.name, party=party)
    
        @observe
        def eats(self, food):
            print "{name} eats {food}".format(name=self.name, food=food)
    
        def digests(self, food):
            print "{name} digests {food}".format(name=self.name, 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.votes("Fidesz")
        print
        jani.eats("Sunday lunch")
        # luckily digestion is not observed
        print
        jani.digests("Sunday lunch")

    public by mprisznyak modified May 3, 2016  376  2  4  3

    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):
    	print(msg)
    
    # action functions
    def meauw():
    	say("meauw")
    
    def woof():
    	say("woof")
    	
    def neigh():
    	say("nyihaha!!!")
    
    # 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"]:
      handle(cmd)
                                        

    public by mprisznyak modified Aug 31, 2013  846  0  5  1

    Factory

    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)
            else:
                s = "This car has {self.seats} seat".format(self=self)
            if self.GPS:
                s += ", it's got a GPS"
            else:
                s += ", it doesn't have a GPS"
            if self.trip_computer:
                s += "and it's got a trip computer. "
            else:
                s += "and it doesn't have a trip computer. "
            return s
    
    class CarFactory(object):
    
        @classmethod
        def make_normal_city_car(self):
            return Car(4)
    
        @classmethod
        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
    
        @classmethod
        def make_luxury_city_car(self):
            return Car(4, True, True)
    
        @classmethod
        def make_normal_cabriolet_car(self):
            return Car(2, make=Car.CABRIOLET)
    
        @classmethod
        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