I am a bit new to the Singleton Design Pattern and cannot understand the following example:
I have a singleton containing a single instance of an ArrayList of type Contact called contactList, where Contact is an object that has a String name and phone number.
Singleton:
public class AllContacts {
private static AllContacts allContacts;
private ArrayList<Contact> contactList;
private AllContacts(){
contactList = new ArrayList<Contact>();
Contact paul = new Contact();
paul.setName("John Smith");
paul.setPhone("1234567890");
contactList.add(paul);
}
public static AllContacts getInstance(){
if(allContacts == null){
allContacts = new AllContacts();
}
return allContacts;
}
public ArrayList<Contact> getContactList(){
return contactList;
}
}
Contact:
public class Contact {
private String name;
private String phone;
public Contact(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
I now get a Contact from the ArrayList in a different class and assign it to a variable called person. If I change the name of person using its setter method this also changes the Contact that is inside the ArrayList:
public class AnotherClass{
...
public void changeName(){
Contact person = AllContacts.getInstance().getContactList().get(0);
person.setName("Steve Smith");
//Prints Steve Smith
System.out.println(AllContacts.getInstance().getContactList().get(0).getName());
}
...
}
I don't quite understand how this works, seeing as I din't change the contactList ArrayList directly, but only another variable that was set equal to one of the items in the ArrayList.