Bon*_*ono 5 c++ java design-patterns
我目前正在阅读四人小组写的《设计模式》一书。在某一时刻,运行时和编译时结构进行了比较。在本节中,写入以下内容:
聚合意味着一个对象拥有另一个对象或对另一个对象负责。一般来说,我们谈论一个物体具有另一个物体或者是另一个物体的一部分。聚合意味着聚合对象及其所有者具有相同的生命周期。
My interpretation of that is something like the following in Java:
public class SomeClass{
private OtherClass; //This is the aggregate object
//...
}
Run Code Online (Sandbox Code Playgroud)
I assume that this is what they mean, and I find that easy to understand. But then they define an acquaintance:
Acquaintance implies that an object merely knows of another object. Sometimes acquaintance is called "association" or the "using" relationship. Acquainted objects may request operations of each other, but they aren't responsible for each other. Acquaintance is a weaker relationship than aggregation and suggests much looser coupling between objects. ... In C++, aggregation can be implemented by defining member variables that are real instances, but it's more common to define them as pointers or references to instances. Aquaintance is implemented with pointers and references as well.
That final bit confuses me. Can it only be achieved through pointers? They're talking about C++ specifically, does this mean it cannot be accomplished in Java? To my understanding an aquaintance relation would be something like this in Java:
public class SomeClass{
///...
public void doSomething(SomeOtherClass some_other_class){
some_other_class.doSomethingElse(); //Is this (an) aquaintance?
}
///...
}
Run Code Online (Sandbox Code Playgroud)
I'm not entirely sure I've got this (aquaintance) concept down. Would anyone be willing to enlighten me if this is the correct way to view things in Java? Or can aquaintance relationships not be achieved in Java, because we don't have pointers?
Finally they say:
Ultimately, acquaintance and aggregation are determined more by intent than by explicit language mechanisms.
What is that supposed to mean? They are just abstract concepts, and not actual implementations or something?
Difference aggregation, acquaintance and composition (as used by Gang Of Four). This was the only question I could find that came close to my own, but it doesn't really help me much. Thanks in advance.
I think you understand everything perfectly. Acquaintance relations can be achieved in Java just like you say. (Java does have pointers; Java references are just a higher level of abstraction than C pointers)
public class SomeClass{
///...
public void doSomething(SomeOtherClass some_other_class){
some_other_class.doSomethingElse(); //yes SomeOtherClass is the Acquaintance
}
///...
}
Run Code Online (Sandbox Code Playgroud)
The GoF book was written before Java was released so it uses C++ terms and concepts that may or may not 100% match with Java.
熟人一词可能意味着比 C++ 的朋友概念更不密切的关系,朋友可以查看和访问另一个对象的私有数据