1

我想使用复合模式将一个对象收到的调用转发给其他对象。

目前,接收端的对象都是相同Abstract类型的,但问题是它们根据具体类型(考虑不同的模型)选择性地接受不同类型的对象作为参数。

据我所知,有两种解决方案,但都不令人满意:

  • 使用 instanceof 检测输入端的类类型对象。这通常被认为是一种不好的做法。
  • 制作尽可能多Lists的输入类型。这带来了一个问题,即List必须添加 a 以适应新的输入类型,并且List必须依次显式处理每个输入类型。

我一直在考虑接口,但到目前为止还没有想出一个可行的想法。这个设计问题的解决方案是什么?复合材料是否合适?

PS:这是在mvc的上下文中。

4

2 回答 2

2

复合模式允许您将对象集合视为叶对象。

我会说你可以做这样的事情:

public interface Command
{
    void execute(Object parameter);
}

public class LeafCommand implements Command
{
    public void execute(Object parameter)
    {  
        // do something for a leaf
    }
}

public class CompositeCommand implements Command
{
    private List<Command> commands;

    void execute(Object parameter)
    {
        for (Command child : commands) 
        { 
           child.execute(parameter);
        }
    }

}

这就是复合材料对我的意义。你是对的 - 如果你必须使用instanceof你做错了。

于 2010-07-12T22:22:45.450 回答
0

I've found the following approach in the StocksMonitor application at Java Practises. This is the update method of the Main view in an mvc context:

  public void update(Observable aObservable, Object aData) {
    fLogger.fine("Notify being broadcast...");
    if (aObservable == fCurrentPortfolio) {
      fLogger.fine("Notified by Current Portfolio...");
      synchTitleBarWithCurrentPortfolio();
    }
    else if (aObservable == fGeneralLookPrefs) {
      fLogger.fine("Notified by General Look...");
      synchGuiWithGeneralLookPrefs();
    }
  }

The references are instances of different models which are used to selectively update corresponding views. This approach respects the composite pattern and allows case-by-case processing according to the parameter instance. Of course, this relies on only one instance of a model being used at runtime.

于 2010-07-13T13:18:56.127 回答