中介者与观察者面向对象的设计模式 [英] Mediator Vs Observer Object-Oriented Design Patterns

查看:163
本文介绍了中介者与观察者面向对象的设计模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 四国帮派 ,在为了解决我的一些问题,遇到了 Mediator 模式。

我以前在我的用于制作一些GUI应用程序的项目。我有点困惑,因为我没有发现两者之间的巨大差异。我浏览了找到差异,但找不到任何适合我的查询的答案。

I had earlier used Observer in my projects for making some GUI application. I am a bit confused as I do not find great difference between the two. I browsed to find the difference but could not find any apt answer for my query.

有些人可以帮助我区分两者之间的一个很好的例子,这清楚地划分了两个?

Could some one help me to differentiate between the two with some good example which clearly demarcates the two?

推荐答案

观察者模式:
定义对象之间的一对多依赖关系,以便在一个对象更改状态,其所有依赖关系将自动通知和更新。

The Observer pattern: Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Mediator模式:
定义一个封装一组对象如何交互的对象。调解员通过明确地保持对象互相引用来促进松耦合,并且可以让您独立地改变其互动。

The Mediator pattern: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

资料来源: dofactory

示例:

观察者模式:
A类可以有零个或多个观察者的类型O注册了。当A中的某些内容被更改时,它通知所有的观察者。

The observer pattern: Class A, can have zero or more observers of type O registered with it. When something in A is changed it notifies all of the observers.

调解器模式:
你有一些类X的实例(或者甚至几个不同的类型:X,Y和Z),并且希望彼此通信(但是你不希望每个人都有明确的引用),所以你创建一个中介类M.每个X的实例都有引用M的共享实例,通过它可以与X(或X,Y和Z)的其他实例进行通信。

The mediator pattern: You have some number of instances of class X (or maybe even several different types:X, Y & Z), and they wish to communicate with each other (but you don't want each to have explicit references to each other), so you create a mediator class M. Each instance of X has a reference to a shared instance of M, through which it can communicate with the other instances of X (or X, Y and Z).

这篇关于中介者与观察者面向对象的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆