首页 \ 问答 \ 如果观察者也是主体,如何应用观察者模式(How to apply observer pattern if observers are also subjects)

如果观察者也是主体,如何应用观察者模式(How to apply observer pattern if observers are also subjects)

我有一个容器面板。 在容器中我有其他面板。 用户可以在任何面板中更改信息。 当面板更改时,应更新所有其他容器并刷新它们呈现的信息。

在正常情况下,观察者模式有一个主题和一群观察者。 在这种情况下,观察者也是主体。

这是设计模式可以解决的问题吗? 我应该如何以良好的OOP风格构建这些对象之间的交互?


I have a container panel. In the container I have n other panels. The user can change the information in any panel. When a panel changes, all other containers should be updated and refresh the information they present.

In a normal situation the observer patter has a single subject and a bunch of observers. In this case the observers are also subjects.

Is this something design patterns can address ? How should I build the interaction between these objects in a good OOP style ?


原文:https://stackoverflow.com/questions/10540608
更新时间:2023-02-20 14:02

最满意答案

我正在试图恢复一个不足的模块(Zoidberg),你可以做的最好的方法是挖掘CPANtesters的结果,以查看出错的地方,以便尝试修复它。

这就是说谷歌地图有一个公共的API,甚至一个简单的Web界面 。 我会试着嘲笑你一个例子,但为了让自己开始尝试用LWP::UserAgentWWW::Mechanize做一些请求,然后解析出结果以找到你的答案。

编辑:好的,这是一个例子。 接近结尾$data是上面链接中描述的JSON响应中包含的数据的hashref。 我也计算了(第一)路线的总距离。

#!/usr/bin/perl

use strict;
use warnings;

use JSON;

use LWP::UserAgent;
my $ua = LWP::UserAgent->new();

my $origin = "60607";
my $destination = "60067";

my $site = 'http://maps.googleapis.com/maps/api/directions/';
my $mode = 'json';

my $page = $site . $mode . '?origin="' . $origin . '"&destination="' . $destination . '"&sensor=false';

my $response = $ua->get( $page );
my $json = $response->content();

my $data = decode_json $json;

my @legs = @{ $data->{'routes'}[0]{'legs'} };
my $distance_meters = 0;
foreach my $leg (@legs) {
    $distance_meters += $leg->{'distance'}{'value'};
}

my $distance_kilometers = $distance_meters / 1000;
my $distance_miles = $distance_kilometers * 0.62137119;
print $distance_miles . " Miles\n";

编辑:现在,因为我在周日下午感到无聊:

perl -e 'use JSON;use LWP::Simple;($s,$e)=@ARGV;$m+=$_->{distance}{value}for@{(decode_json get qq<http://maps.googleapis.com/maps/api/directions/json?origin="$s"&destination="$e"&sensor=false>)->{routes}[0]{legs}};printf"%.2f Miles\n",$m*0.6213e-3' 60607 60067

编辑:现在, Mojolicious系统的一个端口:

perl -Mojo -E '$m+=$_->{distance}{value}for@{g("http://maps.googleapis.com/maps/api/directions/json",form=>{origin=>shift,destination=>shift,sensor=>"false"})->json("/routes/0/legs")};printf"%.2f Miles\n",$m*0.6213e-3' 60607 60067

I am in the process of trying to recover an undermaintained module (Zoidberg) and the best you can do is dig through the results of the CPANtesters to see what went wrong in order to try to fix it.

That said google maps has a public api and even one with a simple web interface. I will try to mock you up an example, but to get yourself started try doing some requests with LWP::UserAgent or WWW::Mechanize and then parse out the results to find your answer.

Edit: Ok here is an example. Near the end $data is a hashref of the data contained in the JSON response described in the link above. I have also calculated the total distance for the (first) route.

#!/usr/bin/perl

use strict;
use warnings;

use JSON;

use LWP::UserAgent;
my $ua = LWP::UserAgent->new();

my $origin = "60607";
my $destination = "60067";

my $site = 'http://maps.googleapis.com/maps/api/directions/';
my $mode = 'json';

my $page = $site . $mode . '?origin="' . $origin . '"&destination="' . $destination . '"&sensor=false';

my $response = $ua->get( $page );
my $json = $response->content();

my $data = decode_json $json;

my @legs = @{ $data->{'routes'}[0]{'legs'} };
my $distance_meters = 0;
foreach my $leg (@legs) {
    $distance_meters += $leg->{'distance'}{'value'};
}

my $distance_kilometers = $distance_meters / 1000;
my $distance_miles = $distance_kilometers * 0.62137119;
print $distance_miles . " Miles\n";

Edit: And now, since I was bored on a Sunday afternoon:

perl -e 'use JSON;use LWP::Simple;($s,$e)=@ARGV;$m+=$_->{distance}{value}for@{(decode_json get qq<http://maps.googleapis.com/maps/api/directions/json?origin="$s"&destination="$e"&sensor=false>)->{routes}[0]{legs}};printf"%.2f Miles\n",$m*0.6213e-3' 60607 60067

Edit: And now, a port of the one liner to the Mojolicious system:

perl -Mojo -E '$m+=$_->{distance}{value}for@{g("http://maps.googleapis.com/maps/api/directions/json",form=>{origin=>shift,destination=>shift,sensor=>"false"})->json("/routes/0/legs")};printf"%.2f Miles\n",$m*0.6213e-3' 60607 60067

相关问答

更多
  • 只需删除变量并像这样调用构造函数: @Test (expected = IllegalArgumentException.class) public void testIllegalCenter() { new Circle(VALID_RADIUS, INVALID_POINT, VALID_COLOR); } Just remove the variable and call the constructor like this: @Test (expected = IllegalArgumen ...
  • 如果您使用的是CMake 3.7或更高版本,则可以使用与测试夹具相关的属性。 对于早期版本的CMake,通过设置REQUIRED_FILES属性,让您的precheck测试成功创建其他测试所依赖的虚拟文件。 If you are using CMake version 3.7 or later, you can use the test fixture related properties. For earlier versions of CMake, have your precheck test cre ...
  • 我可能会使用Spring http调用程序,希望大型弹簧生态系统的支持有所帮助。 它看起来像Hessian和http调用者应该很容易交换。 I'd probably use either Spring http invoker, hoping that the backing by the large spring ecosystem helps. It also looks like Hessian and http invoker should be easily exchangable.
  • 要匹配死组件,您不需要计算类型,只需使用我计算程序集: warnif count > 0 from a in JustMyCode.Assemblies where a.AssembliesUsingMe.Count() == 0 select a 如果要使用程序集匹配类型的条件,可以编写如下内容: warnif count > 0 from a in JustMyCode.Assemblies let typesUser = Application.Types.Using(a) where ...
  • 您的解决方案的问题是,如果有returning false in case the string in question has 奇怪的 length ,您只是returning false in case the string in question has 实际上并非如此,此任务the pass use-cases可以在数学上划分如下: 1) xyz存在于中间,并且在其左侧或右侧有一串长度为x + 1和x的字符串。 将字符串xyz长度设为3,总长度为: (x) + 3 + (x + 1) = 2x + ...
  • 您可以将该特定测试添加到setup()方法中。 这将使所有测试失败的测试都会被跳过,例如 public function setup() { $this->subjectUnderTest = new SubjectUnderTest; $this->assertPreconditionOrMarkTestSkipped(); } public function assertPreconditionOrMarkTestSkipped() { if ($someCondition = ...
  • 我正在试图恢复一个不足的模块(Zoidberg),你可以做的最好的方法是挖掘CPANtesters的结果,以查看出错的地方,以便尝试修复它。 这就是说谷歌地图有一个公共的API,甚至一个简单的Web界面 。 我会试着嘲笑你一个例子,但为了让自己开始尝试用LWP::UserAgent或WWW::Mechanize做一些请求,然后解析出结果以找到你的答案。 编辑:好的,这是一个例子。 接近结尾$data是上面链接中描述的JSON响应中包含的数据的hashref。 我也计算了(第一)路线的总距离。 #!/usr/ ...
  • 您的测试用例不包含任何错误。 它是您的testNG.xml中引发堆栈跟踪的侦听器。 调试TestNGCustomReportListener类的方法generateReport 。 Your test cases do not contain any errors. Its the listener in your testNG.xml that has raised the stack trace. Debug the TestNGCustomReportListener class method gen ...
  • 这是按预期工作 - 用assertEquals '替换那些assert具有相同的效果并打印相同的输出,因为两者完全相同:如果断言失败则抛出异常。 在这种情况下,我所知道的所有测试框架都表现相同:断言失败会导致异常,从而立即终止测试方法的执行。 这是设计的,因为一旦人们的期望被违反,你就不知道你的程序将会做什么 - 方法的其余部分可能取决于那个断言保持为真,并且可能以不可预测和混乱的方式打破。 如果您正在编写类似的测试 test shared void testTwoThings() { assert ...
  • 我认为Web资源的可用性应该是测试库的前提条件。 它本身不应该是一个单独的测试。 因此,您需要在TestFixtureSetup中检查连接。 如果连接失败,则夹具的所有测试都不会运行。 此测试夹具中的所有测试都将标记为失败(如果没有连接则为true),您将收到消息 TestLixtureSetUp在YourLibtraryTests中失败 不幸的是,如果您使用某些消息进行测试失败,NUnit将不会显示其他信息 Assert.NotNull(connection, "Cannot establish conn ...

相关文章

更多

最新问答

更多
  • 以编程方式创建视频?(Create videos programmatically?)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • javascript数组,如何改变这个数组结构(javascript arrays, how to change this array structure)
  • 在ASP.NET Web API中使用多个Get方法进行路由(Routing with multiple Get methods in ASP.NET Web API)
  • 用于backbone.js验证的自定义验证器(Custom validator for backbone.js validation)
  • const char *与其他指针有什么不同?(Is const char * different from other pointers? [duplicate])
  • 无效的列索引,使用PreparedStatement更新(Invalid column index , update using PreparedStatement)
  • watchOS WCSession'已配对'和'watchAppAvailable'不可用(watchOS WCSession 'paired' and 'watchAppAvailable' are unavailable)
  • CalledFromWrongThreadException在Android上执行JUnit测试(CalledFromWrongThreadException exercising JUnit tests on Android)
  • 如何把文件保存到你的应用程序目录中?(How to put\save files into your application directory? (adobe air))
  • 美元符号在Java方法描述符中的含义?(Meanings of dollar sign in Java method descriptor?)
  • font-size的含义是什么:1em / 2em?(What doe the meaning of font-size:1em/2em?)
  • h2元素推动其他h2和div。(h2 element pushing other h2 and div down. two divs, two headers, and they're wrapped within a parent div)
  • 创建一个功能(Create a function)
  • Android - 检测与特定wifi ssid断开连接的正确方法?(Android - Correct way to detect disconnecting from a particular wifi ssid?)
  • 通过Shell脚本将文件转换为另一个文件(Convert File To Another File By Shell Script)
  • 我投了份简历,是电脑编程方面的学徒,面试时说要培训三个月,前面
  • 如何过滤magento废弃的购物车报告集合(How to Filter the magento abandoned cart report collection)
  • PDO语句不显示获取的结果(PDOstatement not displaying fetched results)
  • web api http post传递对象504接收失败(web api http post passing object 504 Receive Failure)
  • Rails从视图编辑模型上的多个属性的方法(Rails way to edit multiple attributes on a model from a view)
  • 总是用{}初始化对象是否是好习惯?(Is it good habit to always initialize objects with {}?)
  • 在方案中编写特殊字符到输出端口(编译器设计)(writing special characters to output port in scheme (compiler design))
  • 电脑等级考试得证有多大用处?
  • Qt冻结循环的原因?(Qt freezing cause of the loop?)
  • 第一次调用函数将无法按预期工作,但下一次工作正常(calling a function on the first time won't work as expected, but next time is working)
  • 如何优化使用BigInteger操作执行时间的代码(How to optimize the code that uses BigInteger operations for execution time)
  • TableView重复youtube-api结果(TableView Repeating youtube-api result)
  • 如何提供个人资料信息,以便Passport.js可以使用它?(how does Profile information should be provided so Passport.js can use it?)
  • 有没有办法初始化jquery数据表中的细节?(is there any way to initialize details in jquery datatable?)