working on it ...

Filters

Explore Public Snippets

Sort by

Found 12k snippets matching: design

    public by lbottaro modified Apr 7, 2014  703  1  6  5

    Observer Listener Design Pattern implementation in java

    The code shows how to realize a simple listener in java, implementing the observer design pattern. The listener defines a callback method, which arguments has the Observes annotation. The observed event is the invocation of methods annotated with annotation IPersonMethodInvoke. In this way the observer will be notified every time the observed me
    package com.test.example.person.listener;
    
    import javax.enterprise.event.Observes;
    
    import com.test.example.interfaces.*;
    
    public class PersonListener {
    
    	public void OnEvent(@Observes @IPersonMethodInvoke String s)
    	{
    		System.out.println("Event callback: " + s);
    	}
    
    }
    

    public by lbottaro modified Apr 7, 2014  1330  5  6  3

    Java stateless EJB implementing Observer design pattern

    This java code shows how to implement a simple stateless EJB 3.0, which implements both a remote interface and the Observer design pattern. The annotation Stateless defines the bean as stateless. The annotation Remote defines which remote interface will be implemented. The EJB will handle request to manage a simple POJO class, named Person, acce
    package com.test.example.ejb;
    
    import java.util.Collection;
    import java.util.List;
    
    import javax.ejb.LocalBean;
    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.enterprise.event.Event;
    import javax.inject.Inject;
    
    import com.test.example.interfaces.*;
    import com.test.example.person.Person;
    import com.test.example.person.manager.PersonManager;
    
    /**
     * Session Bean implementation class PersonEJB
     */
    @Stateless
    @LocalBean
    @Remote(IPerson.class)
    public class PersonEJB implements IPerson{
    
    	@Inject
    	private PersonManager pm;
    	
    	@Inject
    	@IPersonMethodInvoke
    	private Event<String> eventFire;
    
    	/**
    	 * Default constructor.
    	 */
    	public PersonEJB() {
    		// TODO Auto-generated constructor stub
    	}
    
    	@Override
    	public Person addPerson(Person p) {
    		p = pm.addPerson(p);
    		return p;
    	}
    
    	@Override
    	public Person updatePerson(Person p) {
    		p = pm.updatePerson(p);
    		return p;
    	}
    
    	@Override
    	public void deletePerson(int id) {
    		pm.deletePerson(id);
    	}
    
    	@Override
    	public List<Person> getPersonList() {
    		List<Person> personList = pm.getPersonList();
    		eventFire.fire(new String("pippo"));
    		return personList;
    	}
    
    	@Override
    	public Person getPerson(int id) {
    		return pm.getPerson(id);
    	}
    
    	@Override
    	public Collection<Person> searchPersons(String completeName) {
    		return pm.searchPersons(completeName);
    	}
    
    
    }
    

    public by lbottaro modified Apr 7, 2014  1094  1  5  1

    Java Qualifier - Implementing Observer Design Pattern using interface

    This code shows a simple java interface. The Qualifier annotation allows to specify this interface as used by other class. This will allow to implement the Observer / Listener Design pattern.
    package com.test.example.interfaces;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    import javax.inject.Qualifier;
    
    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
    public @interface IPersonMethodInvoke {
    
    }
    

    public by terryc modified Feb 17, 2013  607  1  4  0

    Design pattern in Java: singleton

    Implementation of singleton design pattern in Java
    public class Singleton {
    	static Singleton _singleton;
    	
    	static { 
    		_singleton = new Singleton();
    	}
    	
    	private Singleton() {
    	}
    
    	/**
    	 * Retrieve the only instance available in this JVM
    	 */
    	public static Singleton get() { 
    		return _singleton;
    	}
    }

    public by sTiLL-iLL modified Aug 28, 2014  575  2  6  19

    Stalk yer object(s) and handle'em however you want

    "observer" type js class
    // Eazy Object Stalking....
    
    var events = (function(){
    	  var slotz = {};
    	  return {
    	    	monitor:
    	    	   function(slot, lsnr) {
            	      if(!slotz[slot]) slotz[slot] = {
            	 	        queue: []
            	 	    };
    		          
    		            var idx = slotz[slot].queue.push(lsnr) -1;
    		        },
    		    remove:
    			      function() {
    				        delete slotz[slot].queue[idx];
    			      },
    			  emit:
    	          function(slot, dta) {
    	              if(!slotz[slot] || !slotz[slotz].queue.length) {
    	      	          return;
    	              }
    	              var objLst = slotz[slot].queue;
    	              objLst.forEach(function(ob) {
    	      		         ob(dta || {});
    	       		    });
                }
          }
    })();

    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 JonahM modified May 23, 2014  954  9  5  2

    Google Drive Media in HTML

    How to embed a Drive image on a HTML page. Example: http://drive.google.com/uc?export=view&amp;id=[IMAGE ID] See a demonstration: http://gbpscotland.org/growing-leaders/regional-training/
    <img 
      class="wp-image-892 alignright" 
      title="View the Flyer" 
      alt="Basic Training Flyer" 
      src="http://drive.google.com/uc?export=view&amp;id=0Bws9ea6OV7zYcDAwQ3F4RWZ3elhkUXhDby1aaTFuWlZUcEhJ" 
      height="60%" 
      width="60%"
    >

    public by JonahM modified May 19, 2014  702  3  6  4

    Fluid CSS Rows

    I've realised in my coding experience that I need to To allow for space in the div or row tags when using text. Because everything is responsive on a web page, it's a good idea to use these classes. They work really well. Example: http://j.mp/1oilINn
    
    
    .strip-md{
    	padding-top:80px;
    	padding-bottom:80px;
    	position:relative;
    	overflow:hidden;
    }
    
    .strip-sm{
    	padding-top:30px;
    	padding-bottom:30px;
    }
    
    
    • Public Snippets
    • Channels Snippets