資源描述:
《失血模型,貧血模型,充血模型,脹血模型》由會員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、一、失血模型失血模型簡單來說,就是domainobject只有屬性的getter/setter方法的純數(shù)據(jù)類,所有的業(yè)務(wù)邏輯完全由businessobject來完成(又稱TransactionScript),這種模型下的domainobject被MartinFowler稱之為“貧血的domainobject”。下面用舉一個(gè)具體的代碼來說明,代碼來自Hibernate的caveatemptor,但經(jīng)過我的改寫:一個(gè)實(shí)體類叫做Item,指的是一個(gè)拍賣項(xiàng)目一個(gè)DAO接口類叫做ItemDao一個(gè)DAO接口實(shí)現(xiàn)
2、類叫做ItemDaoHibernateImpl一個(gè)業(yè)務(wù)邏輯類叫做ItemManager(或者叫做ItemService)java代碼:publicclassItemimplementsSerializable{privateLongid=null;privateintversion;privateStringname;privateUserseller;privateStringdescription;privateMonetaryAmountinitialPrice;privateMonetaryA
3、mountreservePrice;privateDatestartDate;privateDateendDate;privateSetcategorizedItems=newHashSet();privateCollectionbids=newArrayList();privateBidsuccessfulBid;privateItemStatestate;privateUserapprovedBy;privateDateapprovalDatetime;privateDatecreated=new
4、Date();//getter/setter方法省略不寫,避免篇幅太長}java代碼:publicinterfaceItemDao{publicItemgetItemById(Longid);publicCollectionfindAll();publicvoidupdateItem(Itemitem);}ItemDao定義持久化操作的接口,用于隔離持久化代碼。java代碼:publicclassItemDaoHibernateImplimplementsItemDaoextendsHibernate
5、DaoSupport{publicItemgetItemById(Longid){return(Item)getHibernateTemplate().load(Item.class,id);}publicCollectionfindAll(){return(List)getHibernateTemplate().find("fromItem");}publicvoidupdateItem(Itemitem){getHibernateTemplate().update(item);}}ItemDaoH
6、ibernateImpl完成具體的持久化工作,請注意,數(shù)據(jù)庫資源的獲取和釋放是在ItemDaoHibernateImpl里面處理的,每個(gè)DAO方法調(diào)用之前打開Session,DAO方法調(diào)用之后,關(guān)閉Session。(Session放在ThreadLocal中,保證一次調(diào)用只打開關(guān)閉一次)java代碼:publicclassItemManager{privateItemDaoitemDao;publicvoidsetItemDao(ItemDaoitemDao){this.itemDao=itemDao
7、;}publicBidloadItemById(Longid){itemDao.loadItemById(id);}publicCollectionlistAllItems(){returnitemDao.findAll();}publicBidplaceBid(Itemitem,Userbidder,MonetaryAmountbidAmount,BidcurrentMaxBid,BidcurrentMinBid)throwsBusinessException{if(currentMaxBid!=n
8、ull&¤tMaxBid.getAmount().compareTo(bidAmount)>0){thrownewBusinessException("Bidtoolow.");}//Auctionisactiveif(!state.equals(ItemState.ACTIVE))thrownewBusinessException("Auctionisnotactiveyet.");//Auctionstillvalidif(item.ge