Confusion using object oriented design .. need help
Let say we have an Order class and OrderManagerService class.
Order class: [some state and methods that act on the state]
- Item[]
- status
OrderManagerService class: [have no state. only following static methods]
- createOrder
- getOrder
Question: Let say we are using a relational DB in the back. Our goal is to update Order status. Well, the status need to get updated in the DB. My concern is where to put the updateStatus method.
- Should I call OrderManagerService.开发者_JAVA技巧getOrder then, call Order.updateStatus?
- or create a new method as OrderManagerService.updateOrderStatus?
well, 1st option seems following encapsulation. But, personally I dont like it as we may end up calling DAO layer from entity objects [perhaps, that might be ok]. Wondering what would be a right design choice and why? any help is greatly appreciated.
Option 2 - create a new method as OrderManagerService.updateOrderStatus?
Why?
Your service layer should encapsulate the logical business unit of work and in your case the UOW is
- get the order from DB
- update the status of the object
- persist the changes
and you would demarcate the updateOrderStatus(...) with a transaction. and the service is still stateless.
I think OrderManagerService should have an array of Order class items. This way you could iterate through each item and update the status there. Or if you are looking for accessing a single order item go directly to it via the Order class and update it there.
In either case with your current setup the updateStatus()
should be in the Order class.
How about observer pattern?
updateStatus() would be in Order class, which would be observed by OrderManagerService class.
Each time you changed status (or anyting else) Manager would see it and do some actions if needed (for example update the status in the DB).
The manager could bind to Order when creating an instance and returning it in getOrder() method.
You could also implement some method to unbind Manager from an order if an instance of the order is destroyed (concern only in unmanaged languages).
Since the title of your question contains "using object-oriented design", I'd put the state transition logic in the Order itself because objects are supposed to encapsulate behavior in addition to data.
Having all behavior contained in Services can be likened to an Anemic Domain Model, which is up to you to decide if it's a bad thing or not - there's a lot of debate over that.
Why is there a separate OrderManagerService class? I'd bung all those methods into Order.
(That's probably not theoretically correct or gang-of-four-compliant design pattern but I dn't care because it would make more sense.)
精彩评论