我试图理解 uml 组合到代码的翻译。 我对狗有内存的三个代码示例有疑问。这三个例子可以被认为是一个组合(uml 意义上的组合)吗?
示例 1
class Memory {
// CODE
}
class Dog {
private Memory variable;
Dog(Memory variable) {
this.variable = variable;
}
}
class Factory {
Dog createDog() {
Memory memory = new Memory() // memory contains reference to object Memory only moment and after create dog don't use it
return new Dog(memory);
}
}
示例 2
class Memory {
// CODE
}
class Dog {
private Memory variable;
Dog(Memory variable) {
this.variable = variable;
}
}
class Factory {
Dog createDog() {
return new Dog(new Memory());
}
}
示例3
class Memory {
// CODE
}
class MemoryFactory {
Memory createMemory() {
return new Memory();
}
}
class Dog {
private Memory variable;
Dog(MemoryFactory memoryFactory) {
this.variable = memoryFactory.createMemory();
}
}
class Factory {
Dog createDog() {
MemoryFactory factory = new MemoryFactory()
return new Dog(factory);
}
}
<小时/>
一个稍微不同的例子:
class Memory {
// CODE
}
class Dog {
private Memory variable;
Dog() {
this.variable = new Memory();
Other other = new Other();
other.method(variable);
}
}
class Other {
void method(Memory memory) {
// code which don't save reference to memory
}
}
这是进一步的组合?
最佳答案
是的;所有示例的组成都是相同的:
class Dog {
private Memory variable;
}
相当于
创建 Dog/Memory 的方式与类之间的连接无关,最终总是相同的。 (组合与结构有关;创建它的方式与行为有关。)
<小时/>关于临时存储 Memory 实例的示例:
编译器很可能会针对没有临时变量的示例进行优化,但更有趣的问题是,如果保留引用会怎样?在这种情况下,Dog-Memory 关系将不再是(UML)复合聚合,而最多是关联或共享聚合(另请参阅 What is the difference between association, aggregation and composition? )
<小时/>关于最后一个示例:没关系,只要您遵循 Thomas 所解释的生命周期管理即可。
关于java - 尝试将 uml 组合翻译成代码 [uml],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45007427/