For a school project I have to design a system using UML, only I have ran into a problem.
Let's say that I have to design a (somewhat overcomplicated) vending machine. It has a class with the Creator pattern that makes controllers: VendingMachine. This class makes a SaleController object for every sale. The machine supports different kinds of payments, so the SaleController creates a Payment object. The job of this class is to request a payment with the CoinMachine or CardReader classes, based on a user input. However, it obviously needs a reference to the CardReader and CoinMachine objects, which are created by the the VendingMachine class.
Would it be better to create a public static readonly object reference in the VendingMachine? Or to pass an object reference to SaleController and then pass it on to Payment?
Thanks!
It seems to me that you need a PaymentService
that is able to encapsulate such logic. This PaymentService
would be the one deciding whether to use CardReader
or CoinMachine
to process the Payment
object.
CardReader
and CoinMachine
should be dependencies of PaymentService
. If you are using Spring, you could create CardReader
and CoinMachine
Beans by annotating them with @Component
and in PaymentService
you just need to make them dependencies (injected via @Autowired
or constructor). If you are not using Spring or any other similar Inversion of Control Framework, your best option would be to create CardReader
and CoinMachine
instances on PaymentService
and keep them as attributes.