質問

I'm trying to make a card game.

some classes I have are: CardModel, CardView; DeckModel, DeckView.

The deck model has a list of card model, According to MVC, if I want to send a card to a deck, I can add the card model to the deck model, and the card view will be added to the deck view by a event handler.

So I have a addCard(CardModel m) in the DeckModel class, but if I want to send a event to add the card view of that model to the deck view, I only know let the model has a reference to view.

So the question is: If the card model and deck model have to have a reference to their view classes to do it? If not, how to do it better?

Update, the code:

public class DeckModel {
private ArrayList<CardModel> cards;

private ArrayList<EventHandler> actionEventHandlerList;

public void addCard(CardModel card){
    cards.add(card);

    //processEvent(event x);
    //must I pass a event that contain card view here?
}

CardModel getCards(int index){
    return cards.get(index);

}

public synchronized void addEventHandler(EventHandler l){
    if(actionEventHandlerList == null)
        actionEventHandlerList = new ArrayList<EventHandler>();

    if(!actionEventHandlerList.contains(l))
        actionEventHandlerList.add(l);
}

public synchronized void removeEventHandler(EventHandler l){
    if(actionEventHandlerList!= null && actionEventHandlerList.contains(l))
        actionEventHandlerList.remove(l);
}

private void processEvent(Event e){
    ArrayList list;

    synchronized(this){
        if(actionEventHandlerList!= null)
            list = (ArrayList)actionEventHandlerList.clone();
        else
            return;
    }
    for(int i=0; i<actionEventHandlerList.size(); ++i){
        actionEventHandlerList.get(i).handle(e);
    }
}
}
役に立ちましたか?

解決

In a good MVC Model shouldn't know about View. To achieve that you can provide your Model with listeners interfaces which Controller will subscribe to. So Controller can update View after Model changes.

In JavaFX there is next support for that: ObservableList, properties and binding. You may take a look at how it's done in ListView: items property is an ObservableList which is monitored by ListView controller which updates view accordingly. So users of ListView aren't aware about anything, they can simply add/remove/change elements of items.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top