Composite: Problem
Using the Composite pattern makes sense only when the core model of your app can be represented as a tree.
仅当应用程序的核心模型可以表示为树时,使用复合模式才有意义。
For example, imagine that you have two types of objects: Products and Boxes. A Box can contain several Products as well as a number of smaller Boxes. These little Boxes can also hold some Products or even smaller Boxes, and so on.
例如,假设您有两种类型的对象: Products和Boxes 。一个Box可以包含多个Products以及许多较小的Boxes 。这些小Boxes还可以容纳一些Products甚至更小的Boxes等等。
Composite: Solution and Structure
How would this method work? For a product, it’d simply return the product’s price. For a box, it’d go over each item the box contains, ask its price and then return a total for this box. If one of these items were a smaller box, that box would also start going over its contents and so on, until the prices of all inner components were calculated. A box could even add some extra cost to the final price, such as packaging cost.
这个方法如何运作?对于产品,它只会返回产品的价格。对于一个盒子,它会检查盒子中包含的每件物品,询问其价格,然后返回该盒子的总计。如果其中一个物品是一个较小的盒子,该盒子也会开始检查其内容,依此类推,直到计算出所有内部组件的价格。盒子甚至可能会在最终价格上增加一些额外成本,例如包装成本。
Decorator: Problem
Initial version
New requirement
Decorator: Solution
Facade:Problem and Solution
Imagine that you must make your code work with a broad set of objects that belong to a sophisticated library or framework. Ordinarily, you’d need to initialize all of those objects, keep track of dependencies, execute methods in the correct order, and so on.As a result, the business logic of your classes would become tightly coupled to the implementation details of 3rd-party classes, making it hard to comprehend and maintain.
想象一下,您必须使您的代码能够与属于复杂库或框架的大量对象一起工作。通常,您需要初始化所有这些对象、跟踪依赖关系、以正确的顺序执行方法等等。因此,类的业务逻辑将与第 3 方类的实现细节紧密耦合,从而难以理解和维护。
- Facade: a simple interface to a complex subsystem which contains lots of moving parts
- Providing limited functionality, only features that clients really care about
- For example: an app that uploads short funny videos may use a professional video conversion library, but all it really needs is a class with encode (filename,format)
- This class is a facade
– Facade:复杂子系统的简单界面,其中包含许多移动部件
– 提供有限的功能,仅提供客户真正关心的功能
– 例如:上传有趣短视频的应用程序可能会使用专业的视频转换库,但所有这些真正需要的是一个带有encode(filename, format)的类——这个类是一个门面