使用单例模式的Java联系人列表程序

时间:2013-11-06 12:00:20

标签: java singleton

我必须制作一个简单的程序,作为联系人列表。该程序具有以下主要功能:添加新联系人,删除联系人,查看所有联系人以及将联系人保存到文件。对我来说,主要的问题是程序必须使用单例模式。我以前从未使用过它。所以我只能写出正常的方式。任何人都可以帮我把它作为单身人士吗?

class Contact{
private String name;
private String address;
private String email;
private String phone;

Contact(String name, String address, String email, String phone){
    this.name=name;
    this.address=address;
    this.email=email;
    this.phone=phone;
}

public Contact() {

}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}


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;
}

@Override
public String toString() {
    return "Contact{" + "name=" + name +  ", address=" + address + ", email=" + email + ", phone=" + phone + '}';
}
public int compareTo(Contact c){
    return name.compareTo(c.getName());
}

public void write(){
    try{
        Contact contact;
        contact = new Contact();
        Contact c = contact;

        File file = new File("ContactList.txt");
        if(!file.exists()){
            file.createNewFile();

            try(PrintWriter writer = new PrintWriter(new FileWriter("ContactList.txt", true))){
                writer.printf("%s\r\n", name  + ", " + address + ", " + email + ", " + phone);
                writer.flush();
                writer.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }

    }catch(Exception e){
        e.printStackTrace();
    }

}
public class ContactList {
 ArrayList<Contact> contactlist = new ArrayList<Contact>();
 Contact contact;
 private int top = 0;

public static void main(String[] args){
    Contact contact;
    contact = new Contact();
    Contact c = contact;
    ContactList list = new ContactList();

    BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
    String choose = "";
    while(true){

        System.out.println("\n[1] Add contact");
        System.out.println("[2] Delete contact");
        System.out.println("[3] View all contacts");
        System.out.println("[4] Edit contact");
        System.out.println("[5] Exit");
        System.out.print("Choose : ");

        try{
            choose = keyIn.readLine(); 
            }catch(Exception e){


                System.out.println("Error");
            }


        if(choose.equals("1")) {
        list.addContact();
        }else if(choose.equals("2")) {
        list.deleteContact();
        }else if(choose.equals("3")) {
        list.viewContacts();
        }else if(choose.equals("4")) {
        list.editContact();
        }else if(choose.equals("5")) {
        System.exit(0);
        }else {
        System.out.println
        ("Error");
        }

    }
}


public void addContact(){
    BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
    String name = "";
    String address = "";
    String email = "";
    String phone = "";

try{
System.out.print("Name: ");
name = keyIn.readLine();
System.out.print("Address ");
address = keyIn.readLine();
System.out.print("E-mail address: ");
email = keyIn.readLine();
System.out.print("Phone number: ");
phone = keyIn.readLine();
}catch(Exception e){
e.printStackTrace();
}
Contact contact = new Contact(name, address, email, phone);   
        contactlist.add(contact);
        top++;
        try{
        contact.write();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public void deleteContact(){
    BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));
    int index = 0;
    if(top == 0){
        System.out.println("Empty contact lis");
    }
    try{
    viewContacts();
    System.out.println("\nChoose number to delete: ");
    index = Integer.parseInt(keyIn.readLine())-1;
       }catch(Exception e){
           e.printStackTrace();
       }
    if(index < 0 || index >= top){
        System.out.println("No contact match");
    }else{

        contactlist.remove(contact);
        top--;
        }
    try{
        contact.write();
    }catch(Exception e){
        e.printStackTrace();
    }


    }
    public void viewContacts(){
    for(int index = 0; index < top; index++){
        System.out.println((index+1)+ " Name " + contactlist.get(index).getName());
        System.out.println("Address: " + contactlist.get(index).getAddress());
        System.out.println("E-mail: " + contactlist.get(index).getEmail());
        System.out.println("Phone: " + contactlist.get(index).getPhone());
    }
   }
    public void editContact(){
    BufferedReader keyIn =  new BufferedReader(new InputStreamReader(System.in));
    int index = 0;
    String name = "";
    String address = "";
    String email = "";
    String phone = "";
    try{
        System.out.print("Edit contact: ");
        index = Integer.parseInt(keyIn.readLine())-1;
        System.out.print("Name: ");
        name = keyIn.readLine();
        System.out.print("Address: ");
        address = keyIn.readLine();
        System.out.print("E-mail: ");
        email = keyIn.readLine();
        System.out.print("Phone: ");
        phone = keyIn.readLine();
    }catch(Exception e){
        e.printStackTrace();
    }
    Contact contact = new Contact(name, address, email, phone);
       contactlist.add(index, contact);
    try{
        contact.write();
    }catch(Exception e){
        e.printStackTrace();
    }
}

}

1 个答案:

答案 0 :(得分:1)

Java中的单例是一个只能为其创建一个实例的类,它为此实例提供了一个全局访问点。单例模式描述了如何存档。

单身人士可以为其他Java对象提供独特的数据或功能来源。例如,您可以使用单例从应用程序中访问数据模型,或者定义应用程序其余部分可以使用的记录器。

Java的可能实现取决于您使用的Java版本。

从Java 6开始,您可以使用单元素枚举类型的单例。根据Joshua Bloch的“Effective Java”一书,这种方式目前是在Java 1.6或更高版本中实现单例的最佳方式。

打包mypackage;

public enum MyEnumSingleton {
  INSTANCE;

  // other useful methods here
}   

在Java 1.6之前,应该是单例的类可以像下面这样定义。     公共课Singleton {           private static Singleton uniqInstance;

      private Singleton() {
      }

      public static synchronized Singleton getInstance() {
        if (uniqInstance == null) {
          uniqInstance = new Singleton();
        }
        return uniqInstance;
      }
      // other useful methods here
    }