UML symbols explained
To explain the visual notation (UML) and common symbols shown in the given diagram:
- the concrete class
Product
(box clipped at top)
- the concrete class
ShoppingCart
(box at bottom)
- the aggregation association between both: a directed connection starting with white-filled diamond from
ShoppingCart
ending with open arrow at Product
.
The UML diagram reads: a ShoppingCart
is composed of 1 Product
. The association has a role denoted by label -cart
. A single Product
(denoted by cardinality next to arrow: 1
) may be contained in 0 or many (denoted by cardinality next to diamond: *
) ShoppingCart
s. But a ShoppingCart
has access (denoted by direction of arrow) to a Product
, not vice-versa.
See also:
Implemented in Java
class Product {
}
class ShoppingCart {
private List<Product> cart; // the role interpreted as private member because minus before
public ShoppingCart(String clientName){
// omitted initializations
this.cart = new ArrayList<>();
}
public ShoppingCart[] getCart(){
final ShoppingCart[] self = new ShoppingCart[1]; // with one element
self[0] = this; // only a self-reference, i.e. this object
return self; // purpose unclear, but as in UML: an array of type ShoppingCart
}
public boolean add(Product product) {
return this.cart.add(product);
}
public boolean remove(Product product) {
return this.cart.remove(product);
}
}
I don't understand the sense, usefulness or purpose of getter getCart
and its return type (array of ShoppingCart
s), but at least we could return a single-element array containing a self-reference.
See also:
Java array of constants
Update
From the author's comment the question's UML changed:
UML was too generic, it was changed into +getCart(): List <Product>
which makes more sense
So the accessor operation (getter) should be adapted to reflect this:
public List<Product> getCart() { // more intent-revealing to name it: getProducts()
return this.cart; // consider a more scoped/expressive name: this.products
}
Note on Naming:
My comments to improve the property name from cart
to products
does not only express the type List<Products>
but conveys the contents (collection of products) and avoids duplicating the context (e.g. ShopingCart.prodcuts
instead ShoppingCart.cart
). For callers from outside the cart is represented as products, but from inside the ShoppingCart
contains/has products (aggregation drawn in UML). Members should be interpreted and named to reflect their purpose from within their scope.
On getter naming convention:
In Java (especially for beans) it is conventional to name getters either after the property they return (pattern get<property>()
) , or for their return-value (e.g. predicate pattern is<Attribute>()
like isCheckedOut()
).