是否有推荐的方法在使用 GWT 的 MVP 中使用观察者模式?

发布于 2024-09-01 08:51:33 字数 398 浏览 4 评论 0原文

我正在考虑使用 GWT 根据 MVP 模式实现用户界面,但对如何进行有疑问。

这些是(一些)我的目标:

  • 演示者对 UI 技术一无所知(即不使用 com.google.* 中的任何内容)
  • 视图对演示者一无所知(尚不确定我是否希望它与模型无关) ,但是)
  • 模型对视图或演示者一无所知(...显然)

我会在视图和演示者之间放置一个接口,并使用观察者模式来解耦两者:视图生成事件并通知演示者。

让我困惑的是 GWT 不支持 java.util.Observer 和 java.util.Observable。这表明就 GWT 而言,我正在做的事情不是推荐的方法,这让我想到了我的问题:使用 GWT 实现 MVP 的推荐方法是什么,特别是考虑到上述目标?你会怎么做?

I am thinking about implementing a user interface according to the MVP pattern using GWT, but have doubts about how to proceed.

These are (some of) my goals:

  • the presenter knows nothing about the UI technology (i.e. uses nothing from com.google.*)
  • the view knows nothing about the presenter (not sure yet if I'd like it to be model-agnostic, yet)
  • the model knows nothing of the view or the presenter (...obviously)

I would place an interface between the view and the presenter and use the Observer pattern to decouple the two: the view generates events and the presenter gets notified.

What confuses me is that java.util.Observer and java.util.Observable are not supported in GWT. This suggests that what I'm doing is not the recommended way to do it, as far as GWT is concerned, which leads me to my questions: what is the recommended way to implement MVP using GWT, specifically with the above goals in mind? How would you do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残月升风 2024-09-08 08:51:33

程序结构

我就是这样做的。 Eventbus 允许演示者(扩展抽象类 Subscriber)订阅属于我的应用中不同模块的事件。每个模块对应于我系统中的一个组件,每个模块都有一个事件类型、一个呈现器、一个处理程序、一个视图和一个模型。

订阅 CONSOLE 类型的所有事件的演示者将接收从该模块触发的所有事件。对于更细粒度的方法,您始终可以让演示者订阅特定事件,例如 NewLineAddedEvent 或类似的事件,但对我来说,我发现在模块级别处理它就足够了。

如果您愿意,可以异步调用演示者的救援方法,但到目前为止,我发现自己几乎不需要这样做。我想这取决于您的具体需求。这是我的 EventBus:

public class EventBus implements EventHandler 
{
    private final static EventBus INSTANCE = new EventBus();
    private HashMap<Module, ArrayList<Subscriber>> subscribers;

    private EventBus()  
    { 
      subscribers = new HashMap<Module, ArrayList<Subscriber>>(); 
    }

    public static EventBus get() { return INSTANCE; }

    public void fire(ScEvent event)
    {
        if (subscribers.containsKey(event.getKey()))
            for (Subscriber s : subscribers.get(event.getKey()))
                s.rescue(event);
    }

    public void subscribe(Subscriber subscriber, Module[] keys)
    {
        for (Module m : keys)
            subscribe(subscriber, m);
    }

    public void subscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).add(subscriber);
        else
        {
            ArrayList<Subscriber> subs = new ArrayList<Subscriber>();
            subs.add(subscriber);
            subscribers.put(key, subs);
        }
    }

    public void unsubscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).remove(subscriber);
    }

}

处理程序附加到组件,负责将本机 GWT 事件转换为专门用于我的系统的事件。下面的处理程序处理 ClickEvents 只需将它们包装在自定义事件中,并在 EventBus 上触发它们以供订阅者处理。在某些情况下,处理程序在触发事件之前执行额外的检查是有意义的,有时甚至在决定天气或不发送事件之前执行额外的检查。当处理程序添加到图形组件时,会给出处理程序中的操作。

public class AppHandler extends ScHandler
{
    public AppHandler(Action action) { super(action); }

    @Override
    public void onClick(ClickEvent event) 
    { 
         EventBus.get().fire(new AppEvent(action)); 
    }

Action 是一个枚举,表示我的系统中数据操作的可能方式。每个事件都使用Action 进行初始化。演示者使用该操作来确定如何更新他们的视图。具有操作 ADD 的事件可能会使演示者向菜单添加新按钮,或向网格添加新行。

public enum Action 
{
    ADD,
    REMOVE,
    OPEN,
    CLOSE,
    SAVE,
    DISPLAY,
    UPDATE
}

由处理程序触发的事件看起来有点像这样。请注意事件如何为其使用者定义接口,这将确保您不会忘记实现正确的救援方法。

public class AppEvent extends ScEvent {

    public interface AppEventConsumer 
    {
        void rescue(AppEvent e);
    }

    private static final Module KEY = Module.APP;
    private Action action;

    public AppEvent(Action action) { this.action = action; }

演示者订阅属于不同模块的事件,然后在它们被触发时救援它们。我还让每个演示者为其视图定义一个接口,这意味着演示者永远不必了解有关实际图形组件的任何信息。

public class AppPresenter extends Subscriber implements AppEventConsumer, 
                                                        ConsoleEventConsumer
{
    public interface Display 
    {
        public void openDrawer(String text);
        public void closeDrawer();
    }

    private Display display;

    public AppPresenter(Display display)
    {
        this.display = display;
        EventBus.get().subscribe(this, new Module[]{Module.APP, Module.CONSOLE});
    }

    @Override
    public void rescue(ScEvent e) 
    {
        if (e instanceof AppEvent)
            rescue((AppEvent) e);
        else if (e instanceof ConsoleEvent)
            rescue((ConsoleEvent) e);
    }
}

每个视图都有一个 HandlerFactory 实例,负责为每个视图创建正确类型的处理程序。每个工厂都使用一个 Module 进行实例化,用于创建正确类型的处理程序。

public ScHandler create(Action action)
{
  switch (module)
  {
    case CONSOLE :
      return new ConsoleHandler(action);

视图现在可以自由地将不同类型的处理程序添加到其组件中,而无需了解确切的实现细节。在此示例中,视图需要知道的只是 addButton 按钮应链接到与操作 ADD 对应的某些行为。这种行为是什么将由捕捉事件的演示者决定。

public class AppView implements Display

   public AppView(HandlerFactory factory)
   {
       ToolStripButton addButton = new ToolStripButton();
       addButton.addClickHandler(factory.create(Action.ADD));
       /* More interfacy stuff */  
   }

   public void openDrawer(String text) { /*Some implementation*/ }
   public void closeDrawer() {  /*Some implementation*/ }

示例

考虑一个简化的 Eclipse,其中左侧有一个类层次结构,右侧有一个代码文本区域,顶部有一个菜单栏。这三个将是由三个不同的演示者提供的三个不同的视图,因此它们将组成三个不同的模块。现在,文本区域完全有可能需要根据类层次结构中的更改进行更改,因此文本区域呈现器不仅订阅从文本区域内触发的事件,还订阅事件是有意义的被从类层次结构中解雇。我可以想象这样的事情(对于每个模块,都会有一组类 - 一个处理程序、一个事件类型、一个演示者、一个模型和一个视图):

public enum Module 
{
   MENU,
   TEXT_AREA,
   CLASS_HIERARCHY
}

现在考虑我们希望我们的视图在删除类文件时正确更新从层次结构来看。这将导致 gui 发生以下更改:

  1. 类文件应从类层次结构中删除
  2. 如果类文件已打开,因此在文本区域中可见,则应将其关闭。

两个演示者(一个控制树视图,一个控制文本视图)都会订阅从 CLASS_HIERARCHY 模块触发的事件。如果事件的操作是REMOVE,那么两个演示者都可以采取适当的操作,如上所述。控制层次结构的演示者可能还会向服务器发送一条消息,以确保已删除的文件确实被删除。这种设置允许模块只需侦听从事件总线激发的事件即可对其他模块中的事件做出反应。几乎没有发生耦合,并且交换视图、演示者或处理程序是完全无痛的。

Program Structure

This is how I did it. The Eventbus lets presenters (extending the abstract class Subscriber) subscribe to events belonging to different modules in my app. Each module corresponds to a component in my system, and each module has an event type, a presenter, a handler, a view and a model.

A presenter subscribing to all the events of type CONSOLE will receive all the events triggered from that module. For a more fine-grained approach you can always let presenters subscribe to specific events, such as NewLineAddedEvent or something like that, but for me I found that dealing with it on a module level was good enough.

If you want you could make the call to the presenter's rescue methods asynchronous, but so far I've found little need to do so myself. I suppose it depends on what your exact needs are. This is my EventBus:

public class EventBus implements EventHandler 
{
    private final static EventBus INSTANCE = new EventBus();
    private HashMap<Module, ArrayList<Subscriber>> subscribers;

    private EventBus()  
    { 
      subscribers = new HashMap<Module, ArrayList<Subscriber>>(); 
    }

    public static EventBus get() { return INSTANCE; }

    public void fire(ScEvent event)
    {
        if (subscribers.containsKey(event.getKey()))
            for (Subscriber s : subscribers.get(event.getKey()))
                s.rescue(event);
    }

    public void subscribe(Subscriber subscriber, Module[] keys)
    {
        for (Module m : keys)
            subscribe(subscriber, m);
    }

    public void subscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).add(subscriber);
        else
        {
            ArrayList<Subscriber> subs = new ArrayList<Subscriber>();
            subs.add(subscriber);
            subscribers.put(key, subs);
        }
    }

    public void unsubscribe(Subscriber subscriber, Module key)
    {
        if (subscribers.containsKey(key))
            subscribers.get(key).remove(subscriber);
    }

}

Handlers are attached to components, and are responsible for transforming native GWT events into events specialised for my system. The handler below deals with ClickEvents simply by wrapping them in a customised event and firing them on the EventBus for the subscribers to deal with. In some cases it makes sense for the handlers to perform extra checks before firing the event, or sometimes even before deciding weather or not to send the event. The action in the handler is given when the handler is added to the graphical component.

public class AppHandler extends ScHandler
{
    public AppHandler(Action action) { super(action); }

    @Override
    public void onClick(ClickEvent event) 
    { 
         EventBus.get().fire(new AppEvent(action)); 
    }

Action is an enumeration expressing possible ways of data manipulation in my system. Each event is initialised with an Action. The action is used by presenters to determine how to update their view. An event with the action ADD might make a presenter add a new button to a menu, or a new row to a grid.

public enum Action 
{
    ADD,
    REMOVE,
    OPEN,
    CLOSE,
    SAVE,
    DISPLAY,
    UPDATE
}

The event that's get fired by the handler looks a bit like this. Notice how the event defines an interface for it's consumers, which will assure that you don't forget to implement the correct rescue methods.

public class AppEvent extends ScEvent {

    public interface AppEventConsumer 
    {
        void rescue(AppEvent e);
    }

    private static final Module KEY = Module.APP;
    private Action action;

    public AppEvent(Action action) { this.action = action; }

The presenter subscribes to events belonging to diffrent modules, and then rescues them when they're fired. I also let each presenter define an interface for it's view, which means that the presenter won't ever have to know anything about the actual graphcal components.

public class AppPresenter extends Subscriber implements AppEventConsumer, 
                                                        ConsoleEventConsumer
{
    public interface Display 
    {
        public void openDrawer(String text);
        public void closeDrawer();
    }

    private Display display;

    public AppPresenter(Display display)
    {
        this.display = display;
        EventBus.get().subscribe(this, new Module[]{Module.APP, Module.CONSOLE});
    }

    @Override
    public void rescue(ScEvent e) 
    {
        if (e instanceof AppEvent)
            rescue((AppEvent) e);
        else if (e instanceof ConsoleEvent)
            rescue((ConsoleEvent) e);
    }
}

Each view is given an instance of a HandlerFactory that is responsible for creating the correct type of handler for each view. Each factory is instantiated with a Module, that it uses to create handlers of the correct type.

public ScHandler create(Action action)
{
  switch (module)
  {
    case CONSOLE :
      return new ConsoleHandler(action);

The view is now free to add handlers of different kind to it's components without having to know about the exact implementation details. In this example, all the view needs to know is that the addButton button should be linked to some behaviour corresponding to the action ADD. What this behaviour is will be decided by the presenters that catch the event.

public class AppView implements Display

   public AppView(HandlerFactory factory)
   {
       ToolStripButton addButton = new ToolStripButton();
       addButton.addClickHandler(factory.create(Action.ADD));
       /* More interfacy stuff */  
   }

   public void openDrawer(String text) { /*Some implementation*/ }
   public void closeDrawer() {  /*Some implementation*/ }

Example

Consider a simplified Eclipse where you have a class hierarchy to the left, a text area for code on the right, and a menu bar on top. These three would be three different views with three different presenters and therefore they'd make up three different modules. Now, it's entirely possible that the text area will need to change in accordance to changes in the class hierarchy, and therefore it makes sense for the text area presenter to subscribe not only to events being fired from within the text area, but also to events being fired from the class hierarchy. I can imagine something like this (for each module there will be a set of classes - one handler, one event type, one presenter, one model and one view):

public enum Module 
{
   MENU,
   TEXT_AREA,
   CLASS_HIERARCHY
}

Now consider we want our views to update properly upon deletion of a class file from the hierarchy view. This should result in the following changes to the gui:

  1. The class file should be removed from the class hierarchy
  2. If the class file is opened, and therefore visible in the text area, it should be closed.

Two presenters, the one controlling the tree view and the one controlling the text view, would both subscribe to events fired from the CLASS_HIERARCHY module. If the action of the event is REMOVE, both preseneters could take the appropriate action, as described above. The presenter controlling the hierarchy would presumably also send a message to the server, making sure that the deleted file was actually deleted. This set-up allows modules to react to events in other modules simply by listening to events fired from the event bus. There is very little coupling going on, and swapping out views, presenters or handlers is completely painless.

街角卖回忆 2024-09-08 08:51:33

我在这些方面为我们的项目取得了一些成果。我想要一个事件驱动的机制(想想标准 jdk 库的 PropertyChangeSupport 和 PropertyChangeListener),但它缺失了。我相信有一个扩展模块,并决定继续使用我自己的扩展模块。您可以在 google 上搜索 propertychangesupport gwt 并使用它或采用我的方法。

我的方法涉及以 MessageHandler 和 GWTEvent 为中心的逻辑。它们分别与 PropertyChangeListener 和 PropertyChangeEvent 具有相同的用途。由于稍后解释的原因,我必须自定义它们。我的设计涉及 MessageExchange、MessageSender 和 MessageListener。交换充当广播服务,将所有事件分派给所有侦听器。每个发送者都会触发由 Exchange 侦听的事件,并且 Exchange 会再次触发这些事件。每个侦听器都会侦听交换,并可以根据事件自行决定(处理或不处理)。

不幸的是,GWT 中的 MessageHandler 遇到了一个问题:“当事件被使用时,无法挂钩新的处理程序”。 GWT 形式给出的原因:持有处理程序的后备迭代器不能由另一个线程同时修改。我必须重写 GWT 类的自定义实现。这是基本的想法。

我本想发布代码,但我现在正在去机场的路上,我会尽快抽出时间尝试发布代码。

编辑1:

还无法获得实际的代码,掌握了我正在为设计文档制作的一些幻灯片,并创建了一个博客条目。

发布我的博客文章的链接:GXT-GWT 应用程序

编辑2:

最后一些代码汤。
发布 1
发布 2
发帖 3

I achieved something on these lines for our project. I wanted a event-driven mechanism (think of PropertyChangeSupport and PropertyChangeListener of standard jdk lib) which were missing. I believe there is an extension module and decided to go ahead with my own. You can google it for propertychangesupport gwt and use it or go with my approach.

My approach involved logic centred around MessageHandler and GWTEvent. These serve the same purpose as that of PropertyChangeListener and PropertyChangeEvent respectively. I had to customize them for reasons explained later. My design involved a MessageExchange, MessageSender and MessageListener. The exchange acts as a broadcast service dispatching all events to all listeners. Each sender fires events that are listened by the Exchange and the exchange the fires the events again. Each listener listens to the exchange and can decide for themselves (to process or not to process) based on the event.

Unfortunately MessageHandlers in GWT suffer from a problem: "While a event is being consumed, no new handlers can be hooked". Reason given in the GWT form: The backing iterator holding the handlers cannot be concurrently modified by another thread. I had to rewrite custom implementation of the GWT classes. That is the basic idea.

I would've posted the code, but I am on my way to airport right now, will try to post the code as soon as I can make time.

Edit1:

Not yet able to get the actual code, got hold of some power-point slides I was working on for design documentation and created a blog entry.

Posting a link to my blog article: GXT-GWT App

Edit2:

Finally some code soup.
Posting 1
Posting 2
Posting 3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文