Something that I've noticed with the Swing archictecture that I try to put into practice is having an interface for the Model objects. For instance, the ListModel interface has 'Getter' or query methods to get the size of the model and elements of the model at a particular index. There are NO 'Setter' methods in the interface. So long as the object that renders the ListModel accepts the ListModel type, the internal attributes cannot be modified.
public interface ListModel { public int getSize(); public Object getElementAt(int index); //add and remove listener methods.... }
public ListModelRenderer { public void render(ListModel model, Writer writer) { int size = model.getSize(); Object obj = null; for (int i = 0; i < size; i++) { obj = model.getElementAt(i); writer.write(obj); } } }
If we created an interface called IEmployee that only had 'Getter' methods than our 'Builder' or UI renderers could only QUERY the object and NOT change the attributes of the IEmployee instance. Besides, what is wrong with asking an employee his name, id, or salary. I realize we might have some security concerns with the id and salary but that can be overcome.
public interface IEmployee { public String getName(); public String getId(); public Money getSalary(); }
public EmployeeRenderer { public void render(IEmployee employee, Writer writer) { writer.write("<b>Employee Name:</b>" + employee.getName() + "<p>"); writer.write("<b>Employee Id:</b>" + employee.getId() + "<p>"); writer.write("<b>Employee salary:</b>" + employee.getSalary() + "<p>"); } }
I find this design pattern easy to use and easy to maintain. Besides, programming to interfaces is usually considered a good idea.
|