Java Reference
In-Depth Information
System Pattern Code Examples
Model-View-Controller (MVC)
This code example provides a component-level MVC pattern to manage a contact in the Personal Information
Manager. The ContactModel class provides the model for this demonstration, in this case storing the contact's
first name, last name, title and organization.
Example A.199 ContactModel.java
1. import java.util.ArrayList;
2. import java.util.Iterator;
3. public class ContactModel{
4. private String firstName;
5. private String lastName;
6. private String title;
7. private String organization;
8. private ArrayList contactViews = new ArrayList();
9.
10. public ContactModel(){
11. this(null);
12. }
13. public ContactModel(ContactView view){
14. firstName = "";
15. lastName = "";
16. title = "";
17. organization = "";
18. if (view != null){
19. contactViews.add(view);
20. }
21. }
22.
23. public void addContactView(ContactView view){
24. if (!contactViews.contains(view)){
25. contactViews.add(view);
26. }
27. }
28.
29. public void removeContactView(ContactView view){
30. contactViews.remove(view);
31. }
32.
33. public String getFirstName(){ return firstName; }
34. public String getLastName(){ return lastName; }
35. public String getTitle(){ return title; }
36. public String getOrganization(){ return organization; }
37.
38. public void setFirstName(String newFirstName){ firstName = newFirstName; }
39. public void setLastName(String newLastName){ lastName = newLastName; }
40. public void setTitle(String newTitle){ title = newTitle; }
41. public void setOrganization(String newOrganization){ organization = newOrganization; }
42.
43. public void updateModel(String newFirstName, String newLastName,
44. String newTitle, String newOrganization){
45. if (!isEmptyString(newFirstName)){
46. setFirstName(newFirstName);
47. }
48. if (!isEmptyString(newLastName)){
49. setLastName(newLastName);
50. }
51. if (!isEmptyString(newTitle)){
52. setTitle(newTitle);
53. }
54. if (!isEmptyString(newOrganization)){
55. setOrganization(newOrganization);
56. }
57. updateView();
58. }
59.
60. private boolean isEmptyString(String input){
61. return ((input == null) || input.equals(""));
62. }
63.
64. private void updateView(){
65. Iterator notifyViews = contactViews.iterator();
 
 
Search WWH ::




Custom Search