两个类之间的“创建” /实例化关系是什么? [英] What is the "creates"/instantiation relationship like between two classes?

查看:169
本文介绍了两个类之间的“创建” /实例化关系是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Gamma等人的设计模式

From Design Patterns by Gamma et al


表示部分或聚合关系的对象引用为
,由底部有钻石的箭头线。箭头指向
已被聚合的类(例如Shape)。

An object reference representing a part-of or aggregation relationship is indicated by an arrowheaded line with a diamond at the base. The arrow points to the class that is aggregated (e.g., Shape).

没有菱形
的箭头线表示相识(例如,LineShape保留对Color对象的引用,而其他
个形状可以共享)。引用的名称可能会出现在底部附近,以将
与其他引用区分开来

An arrowheaded line without the diamond denotes acquaintance (e.g., a LineShape keeps a reference to a Color object, which other shapes may share). A name for the reference may appear near the base to distinguish it from other references

要显示的另一个有用的东西是实例化 >
其他。我们使用虚线箭头来表示这一点,因为OMT不支持
。我们称此为创建
关系。箭头指向实例化的类。在
图c中,CreationTool创建LineShape对象。

Another useful thing to show is which classes instantiate which others. We use a dashed arrowheaded line to indicate this, since OMT doesn't support it. We call this the "creates" relationship. The arrow points to the class that's instantiated. In Figure c, CreationTool creates LineShape objects.

我想了解这本书对创建关系的含义。

I would like to understand what the book means by the "creates" relationship.

当A类实例化B类时,类A是否必须具有引用对象B的字段成员,或者类A必须具有创建并返回对象B的方法?

When class A instantiates class B, must class A have a field member referencing an object B, or must class A have a method which creates and returns object B?

是否存在某些设计模式(例如,在同一本书中进行了描述),其中使用了创建 /实例化关系?我找不到它。

Is there some design pattern (for example, described in the same book) which makes use of the "creates"/instantiation relationship? I couldn't find it.

推荐答案

A创建B 只是意味着A中的代码直接创建B的实例-通过使用 new 关键字。该代码可以位于A的构造函数或任何方法中,也可以位于A内的任何位置。

A creates B simply means the code inside A directly creates instances of B -- by using the new keyword. The code can be in the constructors or any methods of A or anywhere inside A.

担心这种关系的原因是它是 strong 关系,即,它导致类之间的紧密耦合。当类A直接创建类B的实例时,我们不能在希望上下文A来创建B的子类实例的另一个上下文中重用A,而无需修改A的源代码。

The reason this kind of relationship is concerned is that it is a strong relationship, i.e., it causes tight-coupling between classes. When class A directly creates instances of class B, we cannot reuse A in another context where we want A to create instances of a child class of B, without modifying source code of A.

为了具有这种灵活性,我们经常使用Factory Method模式或Abstract Factory模式。在这些模式中,直接创建实例的任务属于A的子类(工厂方法)或具体的工厂类(抽象工厂)。

To have such a flexibility, we often use the Factory Method pattern or the Abstract Factory pattern. In these patterns, the task of directly creating instances belong to a child class of A (Factory Method) or a concrete factory class (Abstract Factory).

这篇关于两个类之间的“创建” /实例化关系是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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