且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Observer模式移动标签(JavaFx)

更新时间:2023-12-04 20:53:46

你可以使用观察者模式这个案例。我假设你在每个客户端的某个地方都有一个连接人员列表。如果这是一些,通知其他人移动事件应该很简单。简单地使ChatPerson可观察如此

You can use the observer pattern in this case. I assume you have a list of connected people somewhere on each client. if this is some it should be quite simple to notify the other people of the move event. Simply make the ChatPerson observable like so

public class ChatPerson {
     //your props here :P...
    private final List<MoveListener> listeners = new ArrayList<MoveListener>();

    private void notifyListeners(MoveEvent e){
        for(MoveListener l : listeners){
             l.onMoveEvent(e);
        }
    }
    public void addMoveListener(MoveListener l){
        this.listeners.add(l);
    }
    public void removeMoveListener(MoveListener l){
        this.listeners.remove(l);
    }

    //i would create a move method but you can do this on setX() and setY()
    public void move(int x,int y){
        this.x=x;
        this.y=y;
        this.notifyListeners(new MoveEvent(this,x,y));
    }
    //your other method...
}

现在用于MoveListener接口。

Now for the MoveListener Interface.

public interface MoveListener{
    public void onMoveEvent(MoveEvent e);
}

和MoveEvent。

And the MoveEvent.

public class MoveEvent{
    public final ChatPerson source;//i could be more generic but you get the ideea
    public final int currentX;
    public final int currentY;
    public MoveEvent(ChatPerson source, int x,int y){
        this.source = source;
        this.currentX = x;
        this.currentY = y;
    }
    //you can make the fields private and getters ofc :P
}

现在每当ChatPerson移动时,它都会以一种漂亮而通用的方式广播它的位置,它会响应这个事件向每个监听器发送它的内容。

在容器类中(具有连接人员列表的那个)只需实现一个MoveListener并将其添加到当前的ChatPerson。

在此实现中,您可以遍历连接人员列表并通过线路发送当前位置 可以这么说。如果没有关于你的应用程序如何实现的更多细节我真的不能给出更好的答案。

希望它有所帮助。

Now whenever the ChatPerson moves, it broadcast its position in a nice and generic way, its up to each listener to its stuff in response to this event.
In the container class (the one with the list of connected people) simply implement a MoveListener and add it to the current ChatPerson.
In this implementation you can iterate over the list of connected people and send the current position "over the wire" so to speak. Without more detail on how your app is implemented I can't really give a better answer.
Hope it this helps.