组合(又名关联)如何成为实现重用的另一种方式?



另一个对象中的对象和第一个对象如何重用组合对象背后的代码 组合对象是什么意思可以在运行时确定?

class Calculator
{
private:
long double operand_1;
long double operand_2;
long double result;
int optr;
int multiplier;
Button One;
//Button Two..
//..through Nine
Button Zero;
}
class Button
{
private:
int x1;
int y1;
int x2;
int y2;
char Label[55];
public:
Button( );
int hit( );
void show( );
void press( );
void select( );
}

我不知道我是否朝着正确的方向前进,我想知道">组合对象可以在运行时确定"的含义? 这里按钮是在计算器类中组成的

这个原则在Effective Java Book的"Item 16"中得到了证明。我认为当说"有利于代码重用的复合而不是继承"时,"组合"一词被用作"遏制"或"关联"的同义词,而不是本着UML的真正组合的精神。Joshua Bloch的"Effective Java"在"Item 16"下提供了很好的例子。

在上面书中的演示示例中,包含实例(集合的子类(通过构造函数传递,并且始终可以在(由客户端(破坏组合之外缓存。在本书的演示中,它也是包含的情况,而不是纯粹的合成(其中组合对象在外部未知(。

代码重用可以通过两种机制来实现,即"继承(白盒("和"遏制(黑盒("。在黑盒重用的情况下,我们(可以(通过在抽象基类/接口的引用中分配子类的实例,在运行时耦合可重用类。原则上,只有当存在"IsA"关系并且我们希望使用对象互换性并获得多态行为的优势时,才应使用继承。

在您的示例中,虽然计算器使用的是按钮,但它不需要动态子类实例。但是当我们说addActionListener((时,Button类将通过Containment使用ActionListener,因为"Button Is Not a Kind of ActionListener"而不是Button"使用"ActionListener。

下面是组合代码重用的示例。请注意,List的实例在PackOfCards外部是未知的,但是在内部PackOfCards将所有功能委托给Concrete List。当PackOfCards的对象被销毁时,List也会被销毁。但是在这里,由于"组成",我们将无法从外部动态更改具体列表。

public class Card {
public enum Suit{SPADE, HEART,DIAMOND,CLUB}
public enum Rank{ACE,QUEEN,KING}// and others
private Suit suit;
private Rank rank;
public Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
}
public class PackOfCards {
private List<Card> cards;
public PackOfCards() {
cards = new LinkedList<Card>();
}
public Card getCard(int index){
return cards.get(index);
}
public void shuffle(){
Collections.shuffle(cards);
}
// other methods
}

最新更新