Java Domain model

Source: Internet
Author: User
Tags in domain ruby on rails

In order to make up for everyone's regret, in this summary of the robbin of the field model of some points of view and everyone's complement, in the website and speech, Robbin will be the domain model initially divided into 4 major categories:
1, Blood loss model
2, anemia model
3, congestion model
4, blood-swelling model
So let's take a look at the specific content of these domain models and their pros and cons:

A model of blood loss

Blood loss model in simple terms, is the domain object only the property of the Getter/setter method of pure data classes, all the business logic completely by business object to complete (also known as

Transactionscript), the domain object under this model is called "Anemic domain Object" by Martin Fowler. Here is a specific code to illustrate that the code

From Hibernate's caveatemptor, but after my rewriting:

An entity class is called an item, which refers to an auction item
A DAO interface class is called Itemdao
A DAO interface implementation class is called Itemdaohibernateimpl
A business logic class is called Itemmanager (or Itemservice)

Java code:

public class Item implements Serializable {
Private Long id = null;
private int version;
private String name;
private User seller;
Private String description;
Private Monetaryamount Initialprice;
Private Monetaryamount Reserveprice;
Private Date StartDate;
Private Date EndDate;
Private Set Categorizeditems = new HashSet ();
Private Collection bids = new ArrayList ();
Private Bid successfulbid;
Private itemstate State;
Private User Approvedby;
Private Date Approvaldatetime;
Private Date Created = new Date ();
Getter/setter method omit not write, avoid length too long
}



Java code:

Public interface Itemdao {
Public Item GetItemByID (Long ID);
Public Collection findall ();
public void UpdateItem (item item);
}



Itemdao defines the interface for the persistence operation, which is used to isolate the persisted code.

Java code:

public class Itemdaohibernateimpl implements Itemdao extends Hibernatedaosupport {
Public Item GetItemByID (Long ID) {
Return (Item) gethibernatetemplate (). Load (item.class, id);
}
Public Collection FindAll () {
Return (List) gethibernatetemplate (). Find ("from Item");
}
public void UpdateItem (item) {
Gethibernatetemplate (). Update (item);
}
}


Itemdaohibernateimpl complete the specific persistence work, please note that the acquisition and release of database resources is handled in Itemdaohibernateimpl, each DAO method calls the

Closes the session after the Session,dao method call is opened before. (Session is placed in threadlocal to ensure that one call is turned off only once)

Java code:

public class Itemmanager {
Private Itemdao Itemdao;
public void Setitemdao (Itemdao itemdao) {This.itemdao = Itemdao;}
Public Bid Loaditembyid (Long ID) {
Itemdao.loaditembyid (ID);
}
Public Collection Listallitems () {
return Itemdao.findall ();
}
Public Bid Placebid (item item, User Bidder, Monetaryamount Bidamount,
Bid currentmaxbid, Bid currentminbid) throws Businessexception {
if (currentmaxbid!= null && currentmaxbid.getamount (). CompareTo (Bidamount) > 0) {
throw new Businessexception ("Bid too low.");
}

Auction is active
if (!state.equals (itemstate.active))
throw new Businessexception ("Auction is not active yet.");

Auction still valid
if (Item.getenddate (). Before (new Date ())
throw new Businessexception ("Can" t place new bid, auction already ended. ");

Create New Bid
Bid newbid = new Bid (Bidamount, item, bidder);

Place bid to this Item
Item.getbids (). Add (Newbid);
Itemdao.update (item); Call DAO to complete the persistence operation
return newbid;
}
}



The management of the transaction is done at the Itemmanger level, Itemmanager implement the specific business logic. In addition to the common CRUD-related simple logic, there is a placebid

The logic, that is, the bidding of the project.

The above is a complete sample code for the first model. In this example, the Placebid,loaditembyid,findall and so on business logic are all implemented in Itemmanager, and

Item only Getter/setter method.

Ii. anemia Model

In simple terms, the domain ojbect contains domain logic that is not dependent on persistence, and the domain logic that relies on persistence is detached to the service layer.
Service (business logic, transaction encapsulation)--> DAO---> Domain object
This is the rich domain object Martin Fowler refers to

An entity class with business logic, that is, domain object is item
A DAO interface Itemdao
A DAO implementation Itemdaohibernateimpl
A business logic object Itemmanager

Java code:

public class Item implements Serializable {
All attributes and Getter/setter methods Ibid, omitted
Public Bid Placebid (User bidder, Monetaryamount Bidamount,
Bid currentmaxbid, Bid currentminbid)
Throws Businessexception {

Check Highest Bid (can also is a different strategy (pattern))
if (currentmaxbid!= null && currentmaxbid.getamount (). CompareTo (Bidamount) > 0) {
throw new Businessexception ("Bid too low.");
}

Auction is active
if (!state.equals (itemstate.active))
throw new Businessexception ("Auction is not active yet.");

Auction still valid
if (This.getenddate (). Before (new Date ())
throw new Businessexception ("Can" t place new bid, auction already ended. ");

Create New Bid
Bid newbid = new Bid (Bidamount, this, bidder);

Place bid to this Item
This.getBids.add (Newbid); Please note that this sentence is transparent and persisted, but cannot be invoked here Itemdao,item cannot be generated on Itemdao

Depend on.

return newbid;
}
}



The business logic of bidding is put into the item. Please note this.getBids.add (newbid); Without the support of Hibernate or JDO, O/R mapping, we cannot actually

Now this transparent and persistent behavior. Note, however, that the item cannot be invoked Itemdao, which is dependent on the Itemdao.

Itemdao and Itemdaohibernateimpl code ditto, omitted.

Java code:

public class Itemmanager {
Private Itemdao Itemdao;
public void Setitemdao (Itemdao itemdao) {This.itemdao = Itemdao;}
Public Bid Loaditembyid (Long ID) {
Itemdao.loaditembyid (ID);
}
Public Collection Listallitems () {
return Itemdao.findall ();
}
Public Bid Placebid (item item, User Bidder, Monetaryamount Bidamount,
Bid currentmaxbid, Bid currentminbid) throws Businessexception {
Item.placebid (bidder, Bidamount, Currentmaxbid, currentminbid);
Itemdao.update (item); DAO must be explicitly invoked to remain persistent
}
}



In the second model, the Placebid business logic is implemented in the item, while the Loaditembyid and FindAll business logic is implemented in Itemmanager. But it's worth noting

Is that even if the placebid business logic is placed in the item, you still need to encapsulate a layer in itemmanager to ensure that the Placebid business logic is managed and persisted

Trigger.

This model is the real domain model that Martin Fowler refers to. In this model, there are three business logic methods: Placebid,loaditembyid and FindAll, now ask

The question is which logic should be placed in the item and which logic should be placed in the Itemmanager. In our case, placebid is placed in the item (but Itemmanager also needs to

Simple encapsulation), Loaditembyid and FindAll are placed in Itemmanager.

What is the principle of segmentation? Rod Johnson put forward the principle is "case by case", high reusability, and domain object state closely related to put in the item, reusability is low

, and the domain object state is not closely related to put in the Itemmanager.

After the discussion above, how to differentiate between domain logic and business logic, I would like to propose an improved principle of distinction:

Domain logic should only be related to the instance state of this domain object, not to the state of a batch of domain object;

When you put a logic into domain object, the domain object should still be independent of the persistence layer frame (HIBERNATE,JDO), and this domain object can still be

With unit testing out of the persistence-layer framework, this domain object is still a complete, self-contained domain that does not depend on the external environment, in which case this logic

is domain logic.
Here is a very certain principle: logic is only related to the state of this object, if only with this object, is domain logic; if logic is a group of domain

The state of object, it is not domain logic, but business logic.


Item Placebid This business logic method does not explicitly rely on the persistent Itemdao interface, so it is placed in the item. Note that if you break out of hibernate this persistence

Framework, item this domain object can be unit tested, and he does not rely on the persistence mechanism of the hibernate. It is an independent, portable, complete, self-contained

The domain object.

The two business logic methods, Loaditembyid and FindAll, must be explicitly dependent on the persistent Itemdao interface, otherwise the business logic cannot be completed. If you're going to take these two

method on the item, the item cannot be detached from the hibernate frame and cannot exist independently of the hibernate frame.

The advantages of this model:
1, each layer one-way dependence, the structure is clear, easy to implement and maintain
2, simple design, the underlying model is very stable
Disadvantages of this model:
1, domain object part of the more closely dependent on the persistence of domain logic was separated to the service layer, it appears not oo
2, the service layer is too thick

Three, congestion model
The congestion model is similar to the second model, and the difference is how to divide the business logic into the belief that most of the business logic should be in domain object (including persistent logic)

, and the service layer should be a thin layer that encapsulates only the transaction and a small amount of logic and does not deal with the DAO layer.
Service (transaction encapsulation)---> Domain object <---> DAO
This model is the second model of the domain object and business object into one. So Itemmanager doesn't have to, under this model, there are only three classes, he

They are:

Item: Contains the entity class information, but also contains all the business logic
Itemdao: Persistence of DAO interface classes
Implementation classes for ITEMDAOHIBERNATEIMPL:DAO interfaces

Since Itemdao and Itemdaohibernateimpl are exactly the same as above, they are omitted.

Java code:

public class Item implements Serializable {
All attributes and Getter/setter methods are omitted
private static Itemdao Itemdao;
public void Setitemdao (Itemdao itemdao) {This.itemdao = Itemdao;}

public static Item Loaditembyid (Long ID) {
Return (Item) Itemdao.loaditembyid (ID);
}
public static Collection FindAll () {
Return (List) Itemdao.findall ();
}

Public Bid Placebid (User bidder, Monetaryamount Bidamount,
Bid currentmaxbid, Bid currentminbid)
Throws Businessexception {

Check Highest Bid (can also is a different strategy (pattern))
if (currentmaxbid!= null && currentmaxbid.getamount (). CompareTo (Bidamount) > 0) {
throw new Businessexception ("Bid too low.");
}

Auction is active
if (!state.equals (itemstate.active))
throw new Businessexception ("Auction is not active yet.");

Auction still valid
if (This.getenddate (). Before (new Date ())
throw new Businessexception ("Can" t place new bid, auction already ended. ");

Create New Bid
Bid newbid = new Bid (Bidamount, this, bidder);

Place bid to this Item
This.addbid (Newbid);
Itemdao.update (this); Calling DAO for explicit persistence
return newbid;
}
}



In this model, all the business logic is in item, and transaction management is implemented in item.
The advantages of this model:
1, more in line with the principles of OO
2, service layer is very thin, only act as a façade role, do not deal with DAO.
Disadvantages of this model:
1. DAO and domain object form bidirectional dependencies, and complex bidirectional dependencies can lead to many potential problems.
2, how to divide the service-level logic and domain-level logic is very ambiguous, in the actual project, due to the design and developers of the level of differences, may lead to the entire structure of chaos and disorder.
3, taking into account the service layer of the transaction package characteristics, the service layer must be all the domain object logic to provide the corresponding transaction encapsulation method, the result is the service completely redefined

Once again all domain logic, very cumbersome, and service transaction encapsulation its meaning is equal to the OO domain logic into the process of service Transactionscript

。 The congestion model is hard to implement in the domain layer of OO in the service layer has become a process, for the web-tier Programmer's point of view, and the anemia model is no different.

1. Transactions I do not want to be managed by the item, but by the container or higher level of the business class to manage.

2. If item is not separated from the management of the persistence layer, such as jdo pm, then itemdao.update (this); is not needed, that is, the item is taken from the database during the transaction and

and the declaration cycle does not exceed the scope of the current transaction.

3. If the item is detached from the persistence layer, that is, the life cycle of the item is beyond the scope of the transaction, it is necessary to display a persistent method called update or Attach, which

It should be done according to the 2nd model that robbin.

Iv. Blood-swelling model
Based on the third disadvantage of the congestion model, some students put forward, simply cancel the service layer, leaving only domain object and DAO two layer, in domain object domain logic above encapsulation

Transaction.
Domain object (transaction encapsulation, business logic) <---> DAO
It seems that Ruby on Rails is the model, and he even merges domain object and DAO.
Advantages of the Model:
1, simplifying the layering
2, also count with Oo
Disadvantages of this model:
1, many not domain Logic service logic is also forced into domain object, causing the domain Ojbect model instability
2, domain object exposed to the Web layer too much information, may cause unexpected side effects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.