This example is divided into two layers of patterns, namely the data layer and the presentation layer
public class: Documentfactory.java
Package Cn.hncu.contact.common;import Java.io.file;import Javax.xml.parsers.documentbuilder;import Javax.xml.parsers.documentbuilderfactory;import Javax.xml.transform.transformer;import Javax.xml.transform.transformerfactory;import Javax.xml.transform.dom.domsource;import Javax.xml.transform.stream.streamresult;import Org.w3c.dom.document;public class Documentfactory {private static Document dom=null;private static file File;static{file=new file ("Xml/users.xml"); try {documentbuilderfactory dbf= Documentbuilderfactory.newinstance ();D ocumentbuilder db=dbf.newdocumentbuilder ();d om=db.parse (file); catch (Exception e) {throw new RuntimeException ("Parse Error" +e.getmessage (), E);}} Private Documentfactory () {}public static Document getdocument () {return DOM;} public static void Save () {try {transformerfactory tff=transformerfactory.newinstance (); Transformer Trans=tff.newtransformer (); Trans.transform (new Domsource (DOM), new Streamresult (file));} catch (Exception e) {e.printstacktrace ();}}}
Tool class:Idgenerate.java
Package Cn.hncu.contact.utils;import Java.util.uuid;public class Idgenerate {private Idgenerate () {}public static String GetID () {string Uuid=uuid.randomuuid (). toString (); Uuid=uuid.replace ("-", ""); return uuid;}}
Presentation layer: Contactaction.java
Package Cn.hncu.contact.cmd;import Java.util.list;import Java.util.map;import java.util.scanner;import Org.w3c.dom.element;import Cn.hncu.contact.dao.dao.contactdao;import Cn.hncu.contact.dao.factory.contactdaofactory;public class Contactaction {private Scanner input=null;private Contactdao dao=null;private Element currentuser=null;private String delids[]=null;public contactaction () {input=new Scanner (system.in);d Ao=contactdaofactory.getcontactdao (); while (true) {System.out.println ("1: Login"); System.out.println ("2: Registration"); System.out.println ("0: Exit"); String option = Input.nextline (), if ("1". Equals (option)) {login ();} else if ("2". Equals (option)) {reg ();} else if ("0". equ ALS (option)) {System.out.println ("safe exit"); private void Login () {System.out.println ("Please enter user name"); String Name=input.nextline (); System.out.println ("Please enter password"); String Pwd=input.nextline (); Element res= (Element) Dao.login (NAME,PWD), if (res==null) {System.out.println ("Login failed!");} else {System.out.println (" Login successful, please select the operation "); currentuser=res;Operation ();}} private void operation () {list<map<string, string>> list=dao.queryallcontacts (currentUser);d elids=new String[list.size ()];int i=1;for (map<string, string>map:list) {String id=map.get ("id");d elids[i-1]=id;i++;} System.out.println ("1: Show All Contacts"); System.out.println ("2: Add Contacts"); System.out.println ("3: Delete Contacts"); System.out.println ("4: Modify Contacts"); System.out.println ("5: Switch Account"); String Sel=input.nextline (), if ("1". Equals (SEL)) {showallcontacts (list),} else if ("2". Equals (SEL)) {addcontact ();} else if ("3". Equals (SEL)) {delcontact ();} else if ("4". Equals (SEL)) {updatecontact ();} else if ("5". Equals (SEL) {return;} Operation ();} private void Updatecontact () {System.out.println ("Please enter the name of the contact to be modified"); String Name=input.nextline (); Boolean boo=dao.checkelement (Currentuser,name); if (!boo) {System.out.println ("no Contact") ;} else {System.out.println ("Please enter updated information"); System.out.println ("name"); String Newname=input.nextline (); System.out.println ("Age"); String Newage=input.nextline (); SYSTEM.OUT.PRINTLN ("Telephone"); String Newtel=input.nextline ();d ao.update (currentUser, name, Newname,newage,newtel); SYSTEM.OUT.PRINTLN ("modified successfully");}} private void Delcontact () {System.out.println ("Enter the number of contacts to delete"); int num=input.nextint (); Input.nextline (); Element Edelcontact=dao.del (currentuser,delids[num-1]); if (edelcontact==null) {System.out.println ("the contact to delete does not exist");} else {String name=edelcontact.getelementsbytagname ("name"). Item (0). Gettextcontent (); System.out.println (name+ "has been deleted!");}} private void Addcontact () {System.out.println ("Please enter information for the contact person"); System.out.println ("Name:"); String name = Input.nextline (); SYSTEM.OUT.PRINTLN ("Tel:"); String Tel = input.nextline (); System.out.println ("Gender:"); String sex = input.nextline ();d ao.add (currentuser,name,tel,sex); System.out.println ("add Success");} private void Showallcontacts (list<map<string, string>> List) {System.out.println ("ordinal \ t name \ t gender \ t Phone");// Table Header System.out.println ("--------------------------------"); int i=1;for (map<string, string>map:list) {String Name=map.get ("name"); String Sex=map.get ("Sex "); String Tel=map.get ("tel"); System.out.println ((i++) + "\ T" +name+ "\ T" +sex+ "\ T" +tel);} private void Reg () {System.out.println ("Please enter a registered user name:"); String regname = Input.nextline (), Boolean boo=dao.checkname (Regname), if (!boo) {System.out.println ("the user name already exists, please re-register"); Reg ();} else {System.out.println ("Please enter the registration password:"); String pwd1 = Input.nextline (); System.out.println ("Please enter the registration password again:"); String pwd2 = Input.nextline (), if (!pwd1.equals (PWD2)) {System.out.println ("two times password inconsistent, re-register"); Reg ();} else {Dao.reg ( REGNAME,PWD1); SYSTEM.OUT.PRINTLN ("registered success");}}} public static void Main (string[] args) {new contactaction ();}}
Data layer:
Dao:ContactDAO.java
Package Cn.hncu.contact.dao.dao;import Java.util.list;import Java.util.map;import org.w3c.dom.element;public Interface Contactdao {Element login (string name, string pwd); List<map<string, string>> queryallcontacts (element CurrentUser), void Add (element user, string name, string Tel, String Sex); Element del (element CurrentUser, string string), void Reg (String regname, String pwd1), Boolean checkname (string regname); Boolean checkelement (element CurrentUser, string name); void update (Element currentUser, String oldname, String newName, S Tring NewAge, String NewTel);}
Factory:ContactDAOFactory.java
Package Cn.hncu.contact.dao.factory;import Cn.hncu.contact.dao.dao.contactdao;import Cn.hncu.contact.dao.impl.contactdaoimpl;public class Contactdaofactory {public static Contactdao Getcontactdao () { return new Contactdaoimpl ();}}
Impl:ContactDAOImpl.java
Package Cn.hncu.contact.dao.impl;import Java.util.arraylist;import Java.util.hashmap;import java.util.List;import Java.util.map;import Org.w3c.dom.document;import Org.w3c.dom.element;import Org.w3c.dom.nodelist;import Cn.hncu.contact.common.documentfactory;import Cn.hncu.contact.dao.dao.contactdao;import Cn.hncu.contact.utils.idgenerate;public class Contactdaoimpl implements Contactdao{private Document dom= Documentfactory.getdocument ();p rivate Element currentuser=null; Element root= (Element) Dom.getfirstchild (); @Overridepublic element Login (string name, string pwd) {NodeList list= Root.getelementsbytagname ("user"); for (int i=0;i<list.getlength (); i++) {element e= (Element) List.item (i); if ( E.getattribute ("name"). Equalsignorecase (name) &&e.getattribute ("pwd"). Equals (PWD) {return e;}} return null;} @Overridepublic list<map<string, string>> queryallcontacts (Element user) {currentuser=user; List<map<string, string>> list=new ARRAYLIST<MAP<STRING,STRING>≫ (); NodeList nodelist=currentuser.getelementsbytagname ("Contact"), for (int i=0;i<nodelist.getlength (); i++) {map< String, string> map=new hashmap<string, string> (); Element eelement= (Element) Nodelist.item (i); try {String id=eelement.getattribute ("id"); Map.put ("id", id); String name=eelement.getelementsbytagname ("name"). Item (0). Gettextcontent (); Map.put ("name", name); String age=eelement.getelementsbytagname ("Age"). Item (0). Gettextcontent (); Map.put (' age ', age); String Tel=eelement.getelementsbytagname ("tel"). Item (0). Gettextcontent (); Map.put ("Tel", tel); String sex=eelement.getelementsbytagname ("Sex"). Item (0). Gettextcontent (); Map.put ("Sex", Sex);} catch (Exception e) {}list.add (map);} return list;} @Overridepublic void Add (Element user, String name, String tel, string sex) {Currentuser=user; Element newcontact=dom.createelement ("contact"); Newcontact.setattribute ("id", Idgenerate.getid ()); Element ename=dom.createelement ("name"); ename.settextcontent (name); Newcontact.appendchild (ename); ELement Etel=dom.createelement ("tel"); etel.settextcontent (tel); Newcontact.appendchild (ETel); Element esex=dom.createelement ("sex"); esex.settextcontent (sex); Newcontact.appendchild (Esex); Currentuser.appendchild (newcontact);D ocumentfactory.save ();} @Overridepublic element del (element user, String idstr) {currentuser=user; NodeList list=currentuser.getelementsbytagname ("Contact"), for (int i=0;i<list.getlength (); i++) {Element econtact = (Element) list.item (i); String Id=econtact.getattribute ("id"), if (Id.equals (IDSTR)) {currentuser.removechild (econtact);D Ocumentfactory.save (); return econtact;}} return null;} @Overridepublic void Reg (String regname, String pwd1) {Element newuser=dom.createelement ("user"); newuser.setattribute ("name", Regname); Newuser.setattribute ("pwd", PWD1); Root.appendchild (NewUser);D ocumentfactory.save ();} @Overridepublic boolean checkname (String regname) {NodeList list=dom.getelementsbytagname ("user"); for (int i=0;i< List.getlength (); i++) {element euser= (Element) List.item (i);(Regname.equalsignorecase (Euser.getattribute ("name"))) {return false;}} return true;} @Overridepublic boolean checkelement (Element user, String name) {currentuser=user; NodeList list=currentuser.getelementsbytagname ("name"), for (int i=0;i<list.getlength (); i++) {element e= (element) List.item (i); if (Name.equalsignorecase (E.gettextcontent ())) {return true;}} return false;} private string Getcontactid (String oldname) {NodeList list=currentuser.getelementsbytagname ("Contact"), for (int i=0;i <list.getlength (); i++) {Element e= (Element) List.item (i), if (E.getelementsbytagname ("name"). Item (0). Gettextcontent (). Equalsignorecase (Oldname)) {return E.getattribute ("id");}} return null;} @Overridepublic void Update (Element user, String oldname, String newName, String newage, String newtel) {this.currentuser= User String Contactid=getcontactid (oldname); NodeList list=currentuser.getelementsbytagname ("Contact"), for (int i=0;i<list.getlength (); i++) {Element econtact = (Element) list.item (i); if (Contactid.equals (ECOntact.getattribute ("id"))) {element ename= (Element) econtact.getelementsbytagname ("name"). Item (0); Ename.settextcontent (NewName); Element eage= (Element) Econtact.getelementsbytagname ("Age"). Item (0), if (eage==null) {eage=dom.createelement ("age") ; Econtact.appendchild (eage);} Eage.settextcontent (NewAge); Element etel= (Element) Econtact.getelementsbytagname ("tel"). Item (0), if (etel==null) {etel=dom.createelement ("ETel") ); Econtact.appendchild (ETel);} Etel.settextcontent (NewTel);D ocumentfactory.save (); break;}}}
XML file:
<?xml version= "1.0" encoding= "UTF-8" standalone= "no"? ><contacts><user name= "Jack" pwd= "1234" >< Contact id= "a001" ><name>tom</name><age>20</age><sex>male</sex><tel >13838384380</tel></contact><contact id= "a002" ><name>rose</name><age>19 </age><sex>Female</sex><tel>13811111111</tel></contact></user>< User Name= "Tom" pwd= "4321" ><contact id= "b001" ><name>Jack</name><age>21</age>< Sex>male</sex><tel>13822222222</tel></contact><contact id= "b002" ><name> rose</name><age>19</age><sex>female</sex><tel>13811111111</tel></ Contact><contact id= "B1DCC603C9684019B68FE7FC85B547DC" ><name>xx</name><tel> 22222222222</tel><sex>male</sex><age>22</age></contact></user>< User Name= "Rose" pwd= "1111" ><contact id= "c001" ><name>Tom</name><age>20</age><sex>Male< /sex><tel>13838384380</tel></contact><contact id= "c002" ><name>jack</name ><age>21</age><sex>Male</sex><tel>13822222222</tel></contact>< /user></contacts>
XML Small item------DOM operation contact (non-graphical interface version)