lundi 30 mars 2020

objects 1:1 relation with "Pass by reference"

I have two classes User and Task:

public class User {

private Task task;
private List<Item> items;

// constructor
public User() {
    this.task = new Task(this);
    this.items = new ArrayList<>();
}

// getters

}

the Task class has a reference to User:

public class Task{

// should be always the same as user.items !!!
private List<Item> items;
private User user;

// constructor
public Task(User user){
    this.user = user;
    // Pass by reference ?
    this.items = user.getItems();
}

public void addItem(Item item){
    this.items.add(item);
}

}

Now my questions:

  1. If I add an item with task.addItem(item) will this item also be added to user.items? Is the lifecycle and the instance of user.items exactly and always the same as task.items.

  2. Actually I have a lot of methods within User.class and want to extract that methods within Task.class. With this, I have a 1:1 relationship between user and task. Is there any other design pattern for that (composition/aggregation).

Aucun commentaire:

Enregistrer un commentaire