Design Patterns in Java

Steven John Metsker, William C. Wake

Mentioned 4

An effective companion to the classic Gang of Four book, Metsker and Wake help Java programmers better understand and apply design patterns.

More on Amazon.com

Mentioned in questions and answers.

I have a hard time explaining code or different development paradigms such as design patterns, etc. In my mind, I know what I am talking about, but when I am explaining something I did to a senior or a peer, I feel I am not being as articulate and therefore not doing justice to them. Sometimes, I feel as if I am trying to hard to explain something or making something more difficult that what it actually is. How do you approach explaining code or other practices to someone or a group of people? What are ways you have improved your articulation of code and practices? Does confidence have anything to do with this?

My personal experience about this:

  • Use diagram more than words, or talking. A good diagram worth thousands of words. Although others may not understand the detail, a diagram can give them a high level idea of how things work.
  • Start with something that the audience can understand, and evolve your solution. My favourite Design Pattern book, 'Head First Design Patterns', is a typical example about this.
  • Make sure everyone is on the same page. Make sure everyone understand the problem before you go into the solution. This sounds really stupid but you cannot imagine how often that people start the discussion with 'OK, let's do something like this ... ' without clarify the problem beforehand.
  • Seeking feedback. Everyone has its own problem about presenting ideas to others. You have to ask your audience about their feelings - too fast? need some check point in the middle to clarify questions? etc.

This is a great question. I don't think computer science majors get enough experience at public speaking and defending their code in college. At least the ones I have interviewed haven't. Here are my thoughts on this.

  1. Listen to what your co-workers are saying, and work hard to make sure they know that you understand their point of view. You can't change anybody's opinion if they think you don't understand their starting point.
  2. Read design patterns book, such as Design Patterns in Java . How they explain theories will help you learn to articulate your own.
  3. Take a public speaking course. Getting passed the nervousness is a big one.
  4. White-board out your ideas, visual aids are an immense help.

i have a hashMap which i would like its data to be viewed in a JTable how ever i am having trouble getting the hashMap amount of columns and rows and the data to be displayed.i have a hashmap which takes a accountID as the key and a object of students in which each students have their data like name,id, age, etc.however referring to the JTable docs, it says i would need ints for the row and column and a multidimension array of type Object. how can i do it? can i change my hashMap into a multidimenion array?

--Edit i have edited my question so it could be more clear , i am fairly new to Java i do not really get what some of you have posted, especially since the work i am doing is quite related to OO and grasping OO concepts is my biggest challenge,

/I have a dataStorage class, the registered user is added to the HashMap with a Key input of his Username, which is getUser ./

import java.util.*;

public class DataStorage 
{
    HashMap<String, Student> students = new HashMap<String, Student>();  
    HashMap<String, Staff> staffMembers = new HashMap<String, Staff>();  
    //Default constructor
    public DataStorage(){
    }

    public void addStaffMember(Staff aAcc) 
    {
     staffMembers.put(aAcc.getUser(),aAcc);
    }

    public void addStudentMember(Student aAcc)
    {
     students.put(aAcc.getUser(),aAcc);
    }

   public Staff getStaffMember(String user)
   {
   return   staffMembers.get(user);
   }

   public Student getStudent(String user)
   {
    return students.get(user);
   }

   public int getStudentRows()
   {
        return students.size();
   }


}

/**** This is a student class which extends Account***/

public class Student extends Account {

    private String studentNRIC;
    private String diploma;
    private String gender;
    private double level;
    private int credits;
    private int age;
    private boolean partTime;
    private boolean havePc;
    private boolean haveChild;

    public Student(String n, String nr, String id, String dep, String user, String pass)
    {
        super(n, dep, user, pass, id);
        studentNRIC = nr;
    }

    public void setPartTime(boolean state)
    {
        if(state == true)
        {
            partTime = true;
        }
        else
        {
            partTime = false;
        }
    }

    public boolean getPartTime()
    {
        return partTime;
    }

    public void setHavePc(boolean state)
    {
        if(state == true)
        {
            havePc = true;
        }
        else
        {
            havePc = false;
        }
    }

    public boolean getHavePc()
    {
        return havePc;
    }

    public void setHaveChild(boolean state)
    {
        if(state == true)
        {
            haveChild = true;
        }
        else
        {
            haveChild = false;
        }
    }

    public boolean getHaveChild()
    {
        return haveChild;
    }
    public void setDiploma(String dip)
    {
        diploma = dip;
    }

    public String getDiploma()
    {
        return diploma;
    }

    public void setCredits(String cre)
    {
        credits = Integer.parseInt(cre);
    }

    public int getCredits()
    {
        return credits;
    }

    public void setGender(String g)
    {
        gender = g;
    }

    public String getGender()
    {
        return gender;
    }

    public void setAge(String a)
    {
        age = Integer.parseInt(a);
    }

    public int getAge()
    {
        return age;
    }
    public void setLevel(String lvl)
    {
        level = Double.parseDouble(lvl);
    }

    public double getLevel()
    {
        return level;
    }
    public void setStudentNRIC(String nr)
    {
        studentNRIC = nr;
    }

    public String getStudentNRIC()
    {
        return studentNRIC;
    }

}

/**** This is a the Account superclass***/

public class Account {

    private String name;
    private String department;
    private String username;
    private String password;
    private String accountID;
    public Account()
    {
    }   
    public Account(String nm,String dep,String user,String pass, String accID) 
    {
        name = nm;
        department = dep;
        username = user;
        password = pass;
        accountID = accID;

    }

    public void setName(String nm)
    {
        name = nm;
    }

    public String getName()
    {
        return name;
    }

    public void setDep(String d)
    {
        department = d;
    }

    public String getDep()
    {
        return department;
    }

    public void setUser(String u)
    {
        username = u;
    }
    public String getUser()
    {
        return username;
    }

    public void setPass(String p)
    {
        password = p;
    }

    public String getPass()
    {
        return password;
    }

    public void setAccID(String a)
    {
        accountID = a;
    }

    public String getAccID()
    {
        return accountID;
    }
}

Your DataStorage is like the StudentRegistration is used in the sample code.

 // TIP: It can be handy to place the student in some order in the Map 
    //      (therefore using the sorted map).
    private SortedMap students = new TreeMap();  
    // QUESTION: Why not use argument name 'student'?
    public void addStudentMember(Student aAcc)
    {
        students.put(aAcc.getUser(),aAcc);
    }
    // Updated implementation
    public void addStudent(Student student)
    {
        students.put(student.getAccID(), student);
    }
 // QUESTION: Would a method name 'getNumberOfStudents' not be better?  
    public int getStudentRows()

For me it is a little unclear why Student extends from Account. The account identification, is that an unique-id, through the hole system? Do staff (users) and student (users) all have that as unique identification? Where / who creates them? If not the system self, it can never be guranteed that they also enter correctly into your system. Even when checking on uniqueness within your system, helps. But who say not someone else (by accedent) used someone else his/her unique id? (How are the student and staff (accounts) created? If these id's are indeed unique, why not use those for placing the student into a SortedMap? If the sorting is not important. Why not just use a List of students?

Is the name parameter unique (by which you place the student in the Map)?

Programming is little more then learning a programming language. As once understanding the OO-language Java it is good to read some more general programming books. In your specific case I would say start with Domain Driven Design. And then continue with books like these Test Driven Development, Refactoring to Patterns and Design Patterns.

i am actually reading a book about design patterns in java and i am a newbie :)

http://www.amazon.com/Design-Patterns-Java-TM-Software/dp/0321333020/ at the chapter about composite pattern i came across a code that puzzles me, a cast to an abstract class, I have also not well understood what happens when the sub-clase calls the constructor of the abstract superclass, can you help me please !!

the cast that i am talking about is in the isTree( Set visited)

        MachineComponent c = (MachineComponent) i.next();
        if (visited.contains(c) || !c.isTree(visited)) 

How can we call the isTree method of the subclass after a cast to his abstract superclass while the isTree superclass method is abstract?

Here are snippets of the two classes:

package com.oozinoz.machine;
/*
 * Copyright (c) 2001, 2005. Steven J. Metsker.
 */

import java.util.*;
import com.oozinoz.iterator.ComponentIterator;

/**
 * Objects of this class represent either individual machines or composites of
 * machines.
 */

public abstract class MachineComponent {

    /*
     * Subclasses implement this to support the isTree() algorithm.
     */

    protected abstract boolean isTree(Set s);

    // rest of class omitted
}

2:

package com.oozinoz.machine;    
/*
 * Copyright (c) 2001, 2005. Steven J. Metsker.
 */

import java.util.*;
import com.oozinoz.iterator.ComponentIterator;
import com.oozinoz.iterator.CompositeIterator;

 /**
 * Represent a collection of machines: a manufacturing line, a bay, or a
 * factory.
 */

public class MachineComposite extends MachineComponent {
    protected List components = new ArrayList();

    /**
     * @param visited a set of visited nodes
     * @return true if this composite is a tree
     * @see MachineComponent#isTree()
     */

    protected boolean isTree(Set visited) {
        visited.add(this);
        Iterator i = components.iterator();
        while (i.hasNext()) {
            MachineComponent c = (MachineComponent) i.next();
            if (visited.contains(c) || !c.isTree(visited)) 
                return false;
        }
        return true;
    }

    // rest of class omitted
}

This is the distinction between runtime type (actual type) and compile-time type.

The typecast to an abstract class MachineComponent is fine, because the actual object instance will actually be some non-abstract subclass of MachineComponent that implements all of the abstract methods.

The abstract MachineComponent class is the compile-time type of the assigned variable. But no actual instance is (or can be) created with that abstract class.

I was thinking of looking into some open source projects to find examples of class design, design patterns, and maybe even some AI / algorithm stuff.

I have had some people recommend against looking at open source projects to learn, but I feel it really works for me to see patterns I've learned and implementations I've considered actually working in published projects.

I was thinking fairly simple games with more focus on algorithms and "computer thinking" would be quite helpful since I am less concerned with visual elements currently.

I thought perhaps card games would be pretty useful (poker, hearts, bridge, etc etc) and perhaps board games.

Does anyone have any recommendations for simple open-source games or programs that might help illustrate good class design and design patterns and/or AI implementation?

Thanks!

I first learned design-patterns using the book Design Patterns in Java.

I understand it's not exactly what you're looking for, but I though the codes provided as example were pretty smart and "reader-friendly".