1

For a website I'm working on, I made an Media Service object that I use in the front end, as well as in the backend (CMS). This Media Service object manipulates media in a local repository (DB); it provides the ability to upload/embed video's and upload images.

In other words, website visitors are able to do this in the front end, but administrators of the site are also able to do this in the backend.

I'ld like this service to mail the administrators when a visitor has uploaded/embedded a new medium in the frontend, but refrain from mailing them when they upload/embed a medium themself in the backend.

So I started wondering whether this is a good case for passing a null object, that mimicks the mail funcionality, to the Media Service in the backend. I thought this might come in handy when they decide the backend needs to have implemented mail functionality as well.

In simplified terms I'ld like to do something like this:

Frontend:

$mediaService = new MediaService( new MediaRepository(), new StandardMailService() );

Backend:

$mediaService = new MediaService( new MediaRepository(), new NullMailService() );

How do you feel about this? Does this make sense? Or am I setting myself up for problems down the road?

4

1 回答 1

3

我是这种模式的粉丝。我也喜欢重命名对象以匹配语义。

如您所知,使用 NullObject 获得的两个好处是:
1) 避免在代码中检查 null
2) 将行为合并到一个对象中,该对象表示返回 null 时语义上发生的情况。

如果您有一些 if 语句在管理员上传时返回 null,那么是的,我认为在对象中捕获它是便宜且可能有用的,即使您为后端上传发送邮件的可能性很小。如果您将邮件服务视为通知服务,那么您可能有 FrontendNotificationService(发送邮件)和 BackendNotificationService(当前不发送邮件,但可能会累积有关上传的有用统计信息(数量、总大小等) .)。

如果以上都不是真的,那么我个人会发现没有 NullMailService 的构造函数更具可读性,而使用 StadndardMailService 的构造函数更具可读性。

好消息是,当您认为它有用时,它很容易进行重构,或者如果您想尝试 NullService 并发现它没有用,则撤消它。

HTH,
绿柱石

于 2010-04-01T18:47:22.220 回答