Imagine I have a class with some required fields and some optional fields and I fill it from xml.
public class Person {
//mandatory
private String FirstName;
private String lastName;
private int Age;
//optional
String city;
String Country;
String Street;
Person Spouse;
String Occuption;
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return Age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getStreet() {
return Street;
}
public void setStreet(String street) {
Street = street;
}
public Person getSpouse() {
return Spouse;
}
public void setSpouse(Person spouse) {
Spouse = spouse;
}
public String getOccuption() {
return Occuption;
}
public void setOccuption(String occuption) {
Occuption = occuption;
}
}
now in main method I will build this object using java beans ( setters)
public static void main(String[] args) {
// TODO Auto-generated method stub
//just for testing field
String xmlParamCity="";
String xmlParamCountry="";
String xmlParamStreet="";
Person newPerson = new Person("Fname", "lastName", 0);
//optional fields
if(!xmlParamStreet.isEmpty())
newPerson.setStreet(xmlParamStreet);
if(!xmlParamCity.isEmpty())
newPerson.setStreet(xmlParamCity);
if(!xmlParamCountry.isEmpty())
newPerson.setStreet(xmlParamCountry);
}
is it a good approach to use builder design pattern to create this object from xml ? if yes how to build the person objects using builder pattern with these if else checks ? any better design pattern I should use ?
Aucun commentaire:
Enregistrer un commentaire