建造者与装饰者模式 [英] Builder Vs Decorator pattern

查看:25
本文介绍了建造者与装饰者模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 您什么时候会使用构建器模式?

据说构建器模式适用于 Pizza 示例.

It is said that builder pattern is appropriate for Pizza example.

为什么不是装饰器?通过将奶酪、意大利辣香肠、培根作为基础披萨的额外装饰.

Why not Decorator ? by treating Cheese, Pepperoni, Bacon as additional decorations on a base pizza.

是不是因为奶酪/意大利辣香肠必须单独构建.我不认为,它们需要单独构建,因为它们可以现成可用.

Is it for the reason that Cheese/Pepperoni have to be built seperately. I don't think, they need to be built seperately as they can be available readymade.

请澄清.我也在寻找装饰器模式的一个很好的现实世界示例,以及为什么它适合该特定示例的原因.谢谢.

Pls clarify. Am also looking for a good real-world example of decorator pattern and reason why it is the apt for that particular example. Thank you.

推荐答案

来自维基百科的装饰器模式文章:

From wikipedia's decorator pattern article:

在面向对象编程中,装饰者模式是一种设计模式允许新的/额外的行为添加到现有对象动态.

In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically.

在比萨完全构建之后,无需再添加配料.你不会吃半个比萨,然后再添加一个配料.

There's no need to add toppings to a Pizza after it has been fully constructed. You don't eat half a pizza and then add another topping to it.

换句话说,建造者模式可以很容易地在构建时构建一个可在独立方向上扩展的对象,而装饰者模式允许你向对象添加功能扩展 施工时间后.使用装饰器模式来构造对象是不好的,因为它会使对象处于不一致(或至少不正确)状态,直到所有必需的装饰器都到位 - 类似于使用 setter 指定可选构造函数参数的 JavaBean 问题.

In other words, the Builder Pattern makes it easy to construct an object which is extensible in independent directions at construction time, while the Decorator Pattern lets you add extensions to functionality to an object after construction time. Using the decorator pattern to construct objects is bad because it leaves the object in an inconsistent (or at least incorrect) state until all the required decorators are in place - similar to the JavaBean problem of using setters to specify optional constructor arguments.

这篇关于建造者与装饰者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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