Design Patterns - Data for the Object

Suppose I have data in a file, or possibly in a database. It can be JSON, XML, YAML, CSV, String [], etc.

I would like to create a model object with this data. For instance:

Data:

{
    "name": "John Doe",
    "age": "30"
}

Model (pseudo code):

class Person {
    Person(name, age) {
        this.name = name;
        this.age = age;
    }
    // business logic
}

Some code that creates Person objects from JSON data (Pseudocode):

peopleArray = [];
recordSet = aJSONReader.read('file');
for (recordSet as r) {
    peopleArray.add(new Person(r[0], r[1]));
}

What would you use to create model objects from data? In my example, I would start supporting JSON. What if I want to change it or support new data formats? How to disable this code? Which design template fits here?

+4
source share
3 answers

Use a strategic template (. ). . JSON, XML, . .

, IDataObjectParser , public List<DataObject> parse(). . , , . .

+2

. , . name age.

interface PersonInput {

    public String getName();

    public int getAge();
}

Person

class Person {

    public Person(PersonInput input) {
        name = input.getName();
        age = input.getAge();
    }

}

PersonInput, (CSV, XML ..).

JSON:

class JsonPersonInput implements PersonInput {

    private String name;
    private int age;

    public JsonPersonInput(String json) throws JSONException {
        JSONObject data = new JSONObject(json);
        name = data.getString("name");
        age = data.getInt("age");

    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

}

new Person(new JsonPersonInput(jsonString))
0

'' , ( DAO).

- Java , Java, .

DAO , PersonDAO getPerson() savePerson().

interface PersonDAO {
    public Person readPerson(String path);
    public void addPerson(Person personToBeSaved);
}

, , JSON, DAO, JsonPersonDAO.

If you use a factory to generate Person objects, you only need to change the DAO implementation that you use in one place when such a need arises. If you generate Person objects from within your class, you only need to change the DAO implementation it uses.

Read on here:

http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/dao.html

0
source

Source: https://habr.com/ru/post/1535911/


All Articles