Reference no: EM133214616
A simple To-do list application. The model would be the code that stores the To-do list items. The view would be the code that displays the To-do list items to the user. The controller would be the code that allows the user to add, remove, and edit To-do list items. The Observer Pattern would be used to connect the model, view, and controller together. Whenever the model is updated (e.g. an item is added, removed, or edited), the Observer Pattern would notify the view and controller so that they can update themselves accordingly.
Model:
public class ToDoList {
private ArrayList<String> items;
public ToDoList() {
items = new ArrayList<String>();
}
public void addItem(String item) {
items.add(item);
}
public void removeItem(String item) {
items.remove(item);
}
public void editItem(String oldItem, String newItem) {
int index = items.indexOf(oldItem);
items.set(index, newItem);
}
public ArrayList<String> getItems() {
return items;
}
}
View:
public class ToDoListView {
public void printToDoList(ToDoList toDoList) {
ArrayList<String> items = toDoList.getItems();
for (String item : items) {
System.out.println(item);
}
}
}
Controller:
public class ToDoListController {
private ToDoList toDoList;
private ToDoListView toDoListView;
public ToDoListController(ToDoList toDoList, ToDoListView toDoListView) {
this.toDoList = toDoList;
this.toDoListView = toDoListView;
}
public void addItem(String item) {
toDoList.addItem(item);
}
public void removeItem(String item) {
toDoList.removeItem(item);
}
public void editItem(String oldItem, String newItem) {
toDoList.editItem(oldItem, newItem);
}
public void updateView() {
toDoListView.printToDoList(toDoList);
}
}
Observer:
public class ToDoListObserver implements Observer {
private ToDoListController toDoListController;
public ToDoListObserver(ToDoListController toDoListController) {
this.toDoListController = toDoListController;
}
}
public class ToDoListTest {
public static void main(String[] args) {
ToDoList toDoList = new ToDoList();
System.out.println(toDoList);
}
}