问题
I always see some classes that is named "ClassNameService", well what is the difference as logic? What is the goal of these service classes?
回答1:
Generally speaking, there could be a hierarchy of domain objects which are controlled by the services. If these domain objects are only data placeholders without behaviour then this is not true to object oriented programming.
Check the following: http://www.martinfowler.com/bliki/AnemicDomainModel.html
More commonly, within OOP, group of domain objects have behavior whose interaction forms business logic and this logic is encapsulated by the Service. Such services are stateful, with their state being comprised of these domain objects. Services may also be stateless and offer self-sufficent functionality, think of a very simple calculator API.
Imagine following example: There is an HTTP request which came to your web application and you must extract data, preform some complex computing and, once done, send this computed data as SOAP message to an endpoint. Once you receive the response, you should return it to the client that sent the original request.
You don't want to force your client to manually invoke the computation and transformation of the input. Instead, you want to simply offer him a service API which encapsulates this logic and returns to him the expected result.
For Spring applications you have the Spring annotation: @Service http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Service.html
来源:https://stackoverflow.com/questions/29715105/what-is-the-service-class-in-programming