1

假设您有一个与平台或其他东西有某种联系的对象。例如,用于连接远程网站的对象,您可以在其中控制各种机器人。

生产者对象用于通过代表这些机器人的连接获取几十个实例。这些对象依赖于第一个对象,因为任何操作都需要通过连接。因此,任何本地代码都只是通过生产者对象进行调用。

机器人 <-> 连接 <-> 机器人对象

原始对象可以为这些实例中的每一个实例提供一定数量的实用方法,这些实例可以将更改返回。但是,这可能会将其变成某种无所不能的“神”类。

在这种情况下,您将如何分离责任?

PS:随意建议一个更好的标题。

4

1 回答 1

1

您所描述的听起来与代理模式非常相似:

  • 有一个Robot接口。
  • 服务器通过具体的实现来控制真实的机器人,比如说RealRobot
  • 客户端有一个Connection对象,它可以返回实现Robot接口的代理,但通过连接将调用转发到真实的机器人。

Connection对象本身将仅提供基本的通信方法(例如发送和接收数据),并且不包含您描述的任何“实用方法”。代理实现将利用这些通信方法将调用中继到服务器。

这是一个例子:

共享界面:

public interface Robot {
  void move(...);
}

服务器实现:

public class RealRobot implements Robot { ... }

客户端库:

public class Connection {
  public Robot getRobot(int id) {
    return new RobotProxy(id, this);
  }

  // ...
  // methods for sending and receiving data
  // ...
}

public class RobotProxy implements Robot {
  private final int id;
  private final Connection conn;

  public RobotProxy(int id, Connection conn) {
    this.id = id;
    this.conn = conn;
  }

  public void move(...) {
    conn.send("move", id, ...);
  }
}
于 2012-09-09T23:25:47.013 回答