Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Java Patterns GDG

Enrique López Mañas
November 22, 2012
390

Java Patterns GDG

Charla para GDG

Enrique López Mañas

November 22, 2012
Tweet

Transcript

  1. Samstag, 24. November 12

    View Slide

  2. What is a
    design pattern
    The solution of a coding problem
    Samstag, 24. November 12

    View Slide

  3. What is a
    design pattern
    (extended)
    Language independent strategies
    OO Oriented
    Generally a reusable solution
    Not a final solution (template)
    Samstag, 24. November 12

    View Slide

  4. More...
    At least 250 types1
    Relationship between them
    -Exclusive
    1The Design Patterns, Java Companion -- by James W. Cooper
    -Natural fitting
    -Leading
    Samstag, 24. November 12

    View Slide

  5. Types
    Creational patterns
    1The Design Patterns, Java Companion -- by James W. Cooper
    Creational patterns
    Behavioral patterns
    J2EE patterns
    Samstag, 24. November 12

    View Slide

  6. Creational:
    Singleton
    One instance of a class or one value accessible
    globally in an application.
    -Ensure unique instance
    -Access instance controlled way
    -Define a value shared by all system
    Samstag, 24. November 12

    View Slide

  7. Creational:
    Singleton
    final class RemoteConnection {
    private Connect con;
    private static RemoteConnection rc = new
    RemoteConnection(connection);
    private RemoteConnection(Connect c) {
    con = c;
    ....
    }
    public static RemoteConnection getRemoteConnection() {
    return rc;
    }
    public void setConnection(Connect c) {
    this(c);
    }
    }
    RemoteConnection rconn = RemoteConnection.getRemoteConnection;
    rconn.loadData();
    Samstag, 24. November 12

    View Slide

  8. Creational:
    Prototype
    Cloning an object by reducing the cost of
    creation.
    -Many subclasses, only differ object type
    -Add/remove objects and runtime
    -Configure an application dynamically
    Samstag, 24. November 12

    View Slide

  9. Creational:
    Prototype
    interface Shape {
    public void draw();
    }
    class Line implements Shape {
    public void draw() {
    System.out.println("line");
    }
    }
    class Square implements Shape {
    public void draw() {
    System.out.println("square");
    }
    }
    class Circle implements Shape {
    public void draw() {
    System.out.println("circle");
    }
    }
    Samstag, 24. November 12

    View Slide

  10. Creational:
    Prototype
    class Painting {
    public static void main(String[]
    args) {
    Shape s1 = new Line();
    Shape s2 = new Square();
    Shape s3 = new Circle();
    paint(s1);
    paint(s2);
    paint(s3);
    }
    static void paint(Shape s) {
    s.draw();
    }
    }
    Samstag, 24. November 12

    View Slide

  11. Structural:
    Adapter
    Convert existing interfaces to a new interface
    to achieve compatibility and reusability. Also
    known as Wrapper pattern.
    Related: Proxy, Decorator or Bridge
    Samstag, 24. November 12

    View Slide

  12. Structural:
    Adapter
    public interface Windowlistener {
    public void windowClosed(WindowEvent e);
    public void windowOpened(WindowEvent e);
    public void windowIconified(WindowEvent e);
    public void windowDeiconified(WindowEvent e);
    public void windowActivated(WindowEvent e);
    public void windowDeactivated(WindowEvent e);
    public void windowClosing(WindowEvent e);
    }
    public class WindowAdapter implements WindowListner{
    public void windowClosed(WindowEvent e){}
    public void windowOpened(WindowEvent e){}
    public void windowIconified(WindowEvent e){}
    public void windowDeiconified(WindowEvent e){}
    public void windowActivated(WindowEvent e){}
    public void windowDeactivated(WindowEvent e){}
    public void windowClosing(WindowEvent e){}
    }
    Samstag, 24. November 12

    View Slide

  13. Structural:
    Adapter
    import javax.swing.*;
    import java.awt.event.*;
    class Test extends JFrame {
    public Test () {
    setSize(200,200);
    setVisible(true);
    addWindowListener(new Closer());
    }
    public static void main(String[] args) {
    new Test();
    }
    class Closer extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    }
    }
    Samstag, 24. November 12

    View Slide

  14. Structural:
    Façade
    Make a complex system simpler by providing a
    unified or general interface.
    -Make an entry point to your subsystems.
    -Minimize communication and independency
    -Security and performance considerations
    Samstag, 24. November 12

    View Slide

  15. Structural:
    Façade
    interface General {
    public void accessGeneral();
    }
    interface Special extends General {
    public void accessSpecial();
    }
    interface Private extends General {
    public void accessPrivate();
    }
    class GeneralInfo implements General {
    public void accessGeneral() {
    ! //...
    }
    //...
    }
    Samstag, 24. November 12

    View Slide

  16. Structural:
    Façade
    class SpecialInfo implements Special{
    public void accessSpecial() {
    //...
    }
    public void accessGeneral() {}
    //...
    }
    class PrivateInfo implements Private, Special {
    public void accessPrivate() {
    ! // ...
    }
    public void accessSpecial() {
    ! //...
    }
    public void accessGeneral() {
    ! // ...
    }
    //...
    }
    Samstag, 24. November 12

    View Slide

  17. Structural:
    Façade
    class Connection {
    //...
    if (user is unauthorized) throw new Exception();
    if (user is general) return new GeneralInfo();
    if (user is special) return new SpecialInfo();
    if (user is executive) return new PrivateInfo();
    //...
    }
    Samstag, 24. November 12

    View Slide

  18. Behavioral:
    Memento
    Record states
    -Need undo/redo features.
    Samstag, 24. November 12

    View Slide

  19. Behavioral:
    Memento
    class Memento {
    int num;
    Memento(int c) {
    num = c;
    }
    int getNum() {
    return num;
    }
    }
    Samstag, 24. November 12

    View Slide

  20. Behavioral:
    Memento
    class BtnDice extends JButton implements Command {
    Mediator med;
    BtnDice(ActionListener al, Mediator m) {
    super("Throw Dice");
    addActionListener(al);
    med = m;
    med.registerDice(this);
    }
    public void execute() {
    med.throwit();
    }
    }
    class BtnClear extends JButton implements Command {
    Mediator med;
    BtnClear(ActionListener al, Mediator m) {
    super("Clear");
    addActionListener(al);
    med = m;
    med.registerClear(this);
    }
    public void execute() {
    med.clear();
    }
    }
    Samstag, 24. November 12

    View Slide

  21. Behavioral:
    Memento
    class BtnPrevious extends JButton implements Command {
    Mediator med;
    BtnPrevious(ActionListener al, Mediator m) {
    super("Previous");
    addActionListener(al);
    med = m;
    med.registerPrevious(this);
    }
    public void execute() {
    med.previous();
    }
    }
    class LblDisplay extends JLabel{
    Mediator med;
    LblDisplay (Mediator m) {
    super("0",JLabel.CENTER);
    med = m;
    med.registerDisplay(this);
    setBackground(Color.white);
    setBorder(new EtchedBorder(Color.blue, Color.green));
    Font font = new Font("Arial",Font.BOLD,40);
    setFont(font);
    }
    }
    Samstag, 24. November 12

    View Slide

  22. Behavioral:
    Memento
    Class Mediator {
    BtnDice btnDice;
    BtnPrevious btnPrevious;
    BtnClear btnClear;
    LblDisplay show;
    java.util.List list, undo;
    boolean restart = true;
    int counter = 0, ct = 0;
    //....
    Mediator() {
    list = new ArrayList();
    undo = new ArrayList();
    }
    void registerDice(BtnDice d) {
    btnDice = d;
    }
    void registerClear(BtnClear c) {
    btnClear = c;
    }
    void registerPrevious(BtnPrevious p) {
    btnPrevious = p;
    }
    Samstag, 24. November 12

    View Slide

  23. Behavioral:
    Memento
    void registerDisplay(LblDisplay d) {
    show = d;
    }
    void throwit() {
    show.setForeground(Color.black);
    int num = (int)(Math.random()*6 +1);
    int i = counter++;
    list.add(i, new Integer(num));
    undo.add(i, new Memento(num));
    show.setText(""+num);
    }
    Samstag, 24. November 12

    View Slide

  24. Behavioral:
    Memento
    void previous() {
    show.setForeground(Color.red);
    btnDice.setEnabled(false);
    if (undo.size() > 0) {
    ct = undo.size()-1;
    Memento num = (Memento)undo.get(ct);
    show.setText(""+num.getNum());
    undo.remove(ct);
    }
    if (undo.size() == 0)
    show.setText("0");
    }
    void clear() {
    list = new ArrayList();
    undo = new ArrayList();
    counter = 0;
    show.setText("0");
    btnDice.setEnabled(true);
    }
    }
    Samstag, 24. November 12

    View Slide

  25. Behavioral:
    Memento
    class MementoDemo extends JFrame implements
    ActionListener {
    Mediator med = new Mediator();
    MementoDemo() {
    JPanel p = new JPanel();
    p.add(new BtnDice(this,med));
    p.add(new BtnPrevious(this,med));
    p.add(new BtnClear(this,med));
    JPanel dice = new JPanel();
    LblDisplay lbl = new LblDisplay(med);
    dice.add(lbl);
    getContentPane().add(dice, "Center");
    getContentPane().add(p, "South");
    setTitle("Memento pattern example");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(400,200);
    setVisible(true);
    }
    public void actionPerformed(ActionEvent ae) {
    Command comd = (Command)ae.getSource();
    comd.execute();
    }
    Samstag, 24. November 12

    View Slide

  26. Behavioral:
    Memento
    public static void main(String[] args) {
    new MementoDemo();
    }
    }
    Samstag, 24. November 12

    View Slide

  27. Behavioral:
    Observer
    One object changes state, all of its dependents
    are updated automatically.
    -Publish or subscription
    -Broadcast communication
    Samstag, 24. November 12

    View Slide

  28. Behavioral:
    Observer
    Samstag, 24. November 12

    View Slide

  29. Behavioral:
    Observer
    public class EventSource extends Observable implements Runnable
    {
    public void run() {
    try {
    final InputStreamReader isr = new
    InputStreamReader(System.in);
    final BufferedReader br = new BufferedReader(isr);
    while (true) {
    String response = br.readLine();
    setChanged();
    notifyObservers(response);
    }
    }
    catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    Samstag, 24. November 12

    View Slide

  30. Behavioral:
    Observer
    public class ResponseHandler implements Observer {
    private String resp;
    public void update(Observable obj, Object arg) {
    if (arg instanceof String) {
    resp = (String) arg;
    System.out.println("\nReceived Response: " + resp );
    }
    }
    }
    Samstag, 24. November 12

    View Slide

  31. Behavioral:
    Observer
    public class MyApp {
    public static void main(String[] args) {
    System.out.println("Enter Text >");
    // create an event source - reads from stdin
    final EventSource eventSource = new EventSource();
    // create an observer
    final ResponseHandler responseHandler = new
    ResponseHandler();
    // subscribe the observer to the event source
    eventSource.addObserver(responseHandler);
    // starts the event thread
    Thread thread = new Thread(eventSource);
    thread.start();
    }
    }
    Samstag, 24. November 12

    View Slide

  32. Java MVC
    -MVC
    -Business Delegate
    -Data Access Object
    Samstag, 24. November 12

    View Slide

  33. The design patterns may just be a sign of some
    missing features of a given programming
    language (Java or C++ for instance).
    Peter Norvig demonstrates that 16 out of the
    23 patterns in the Design Patterns book (that is
    primarily focused on C++) are simplified or
    eliminated (via direct language support) in Lisp..
    Moreover, inappropriate use of patterns may
    unnecessarily increase complexity
    Samstag, 24. November 12

    View Slide

  34. Books:
    -Clean Code (Clean Code: A Handbook of Agile Software
    Craftsmanship (Robert C. Martin))
    -The Design Patterns, Java Companion (James W. Cooper)
    Websites:
    http://www.oracle.com/technetwork/java/index.html
    http://c2.com/cgi/wiki?PeopleProjectsAndPatterns
    Samstag, 24. November 12

    View Slide

  35. Thank you !
    + http://goo.gl/t4AVh
    @eenriquelopez
    http://www.neo-tech.es
    Samstag, 24. November 12

    View Slide