Giáo trình môn Kiến trúc và thiết kế phần mềm

Tài liệu gồm 198 trang, gồm 11 chương chính bao gồm các kiến thức cơ bản liên quan đến các khái niệm cơ bản về thiết kế kiến trúc và các kiểu kiến trúc, mô hình hóa kiến trúc,... giúp bạn ôn luyện và nắm vững kiến thức môn học. Mời bạn đọc đón xem!


GIÁO TRÌNH

 
 - 2017

 .................................................................................................... i
  .............. 1
1.1  ............................................................................................ 1
 ........................................................................................................ 1
 .......................................................................................... 1
 ......................................................................................... 2
1.2  ................................................................................................. 3
1.3  ........................................................................................ 4
1.3.1  ........................................................................................................................................ 5
1.3.2  .................................................................................................................................... 5
1.3.3  ........................................................................................................................................... 6
1.3.4  ........................................................................................................................................ 7
1.3.5  ................................................................................................................................ 7
1.3.6 ................................................................................................................................. 7
1.3.7  ........................................................................................................................10
1.4 K ......................................................................................................................... 10
 ................................................................................................................................... 10
.......... 12
 .......................................................................... 12
 .................................................................................................13
 ...................................................................13
 ..........................................................................................................13
 ..........................................................................................................................14
2.2  ................................................................ 14
 ....................................................................................................14
 ............................................................................................................15
 .................................................................................................. 16
 ........................................................................................................16
 ..............................................................................................18
 ..........................................................................................................19
 ............................................................................................................20
......................................................................................................22
- ..................................................................................................................23
 ..................................................................................................24
 ......................................................................................................26
 ......................................................................................................................... 27
 ................................................................................................................................... 27
 ..................................................... 28
 ..................................................................... 28
 .............................................................................................28
 ....................................................................................................29
 ...............................................................................30
 ...................................................................................................31
n ......................................................................................................33
 ..................................................................................................... 34
 .............................................................................................................34
3. ....................................................................................................35
3.3  ...................................................................... 35
 ...........................................................................................35
 ......................................................................................................36
 .............................................................................................................................38
ý ............................................................................................................................41
 ......................................................................................................................... 42
 ................................................................................................................................... 42
 ......... 43
4.1  ...................................................................................................................... 43
 ...................................................43
4.1.2  .................................................................................................................45
4.2  ........................................... 46
4 ...................................................................................................46
......................................................................................................46
 ...... 49
 ........................................... 50
 .....................................................................................................................50
 ........................................................................................................................51
 ......................................................................................................................... 52
 ................................................................................................................................... 53
 ......................................... 54
 .............................................................................................................. 54
 ..........................................................................54
5.1.2. J2EE Server ................................................................................................................................54
5.1.3. Container ....................................................................................................................................55
B .........................................................................................................................56
 ............................................................................ 56
 ................................................................................................................56
5.2.2. EJB 3.0 .......................................................................................................................................57
5.2.3 Bean phiên ...................................................................................................................................58
 ............................................................................................................59
 ...............................................................................................................................60
-Driven Beans) ............................................................68
 ....................................................................................... 69
5.3.1 Kt hp các kt nng b ........................................................................................................70
5.3.2 Kt ni lng lng b ..................................................................................................70
5.3.3 Truyn thông t xa và cc b .....................................................................................................70
5.3.4 Các tham chin các bean thc th ........................................................................70
5.3.5 Kt hp các kt ni gia các bean thc th .................................................................................70
 ........................................................................................ 72
5.5 CASE STUDY .................................................................................................................... 74
 ...............................................................................................................................74
 ...............................................................................................78
 ........................................................................................................................ 82
 ................................................................................................................................... 82
N .NET ................................................ 84
 ...................................................................................................................... 84
 ...................................................................................................84
 CLR. ...........................................................................................85
 ...............................................................................................................87
6.2. MÔ HÌNH THÀNH PHN CA .NET .......................................................................... 88
 ........................................................................................................ 93
 ...........................................................................................................93
 .....................................94
6.3 ............................................................96
 ...................................................99
6.4 MÔ HÌNH TRIN KHAI THÀNH PHN .NET ......................................................... 100
 ........................................................................................................................101
 ............................................................................................................101
 ....................................................................................................................... 104
 ................................................................................................................................. 104
 .......................................... 105
 ...................................................................................... 105
 ..................................................................................... 106
  ...................................................................................... 107
 .......................................................................................... 109
 ..................................................................................................109
 ...........................................................................................109
 ....................................................................................................................... 110
 ................................................................................................................................. 111
 ......................................... 112
 ..................................................................... 112
..................................................................................................................................112
 .............................................................................................................................112
 ...................................................................................................................113
 ..........................................................................................................................................114
 ..................................................................................... 116
..................................................................................................................................116
 .............................................................................................................................116
 ...................................................................................................................116
 ..........................................................................................................................................116
  .................................................................. 119
..................................................................................................................................119
 .............................................................................................................................119
 ...................................................................................................................120
 ..........................................................................................................................................120
 .......................................................................................... 121
..................................................................................................................................125
 .............................................................................................................................125
 ...................................................................................................................126
 ..........................................................................................................................................126
 .................................................................................... 128
..................................................................................................................................128
8.5.2  .............................................................................................................................128
 ...................................................................................................................128
 ..........................................................................................................................................129
 ....................................................................................................................... 129
 ................................................................................................................................. 129
 ......................................... 130
 .............................................................................................................. 130
..................................................................................................................................130
 .............................................................................................................................130
 ...................................................................................................................131
 ..........................................................................................................................................131
 ................................................................................................................. 131
..................................................................................................................................131
 .............................................................................................................................132
 ...................................................................................................................132
 ..........................................................................................................................................133
 ........................................................................................................ 135
..................................................................................................................................135
 .............................................................................................................................135
 ...................................................................................................................136
 ..........................................................................................................................................136
 ....................................................................................................... 137
..................................................................................................................................137
 .............................................................................................................................138
 ...................................................................................................................138
 ................................................................................................................ 141
..................................................................................................................................141
 .............................................................................................................................142
 ...................................................................................................................142
 ..........................................................................................................................................143
 ........................................................................................................ 145
..................................................................................................................................145
g ...................................................................................................................146
 ..........................................................................................................................................146
 ................................................................................................................... 148
..................................................................................................................................148
 .............................................................................................................................148
 ...................................................................................................................149
 ..........................................................................................................................................149
 ....................................................................................................................... 151
 ................................................................................................................................. 151
I ........................................... 153
 ................................................................................... 154
................................................................................................................................154
10.1. ...........................................................................................................................154
 .................................................................................................................155
 ........................................................................................................................................155
 ......................................................................................................... 158
................................................................................................................................158
 ...........................................................................................................................159
 .................................................................................................................160
 ........................................................................................................................................160
 .......................................................................................................... 161
................................................................................................................................161
 ...........................................................................................................................161
 .................................................................................................................162
 ........................................................................................................................................162
 .................................................................................................. 163
................................................................................................................................163
 ...........................................................................................................................164
 .................................................................................................................164
 ........................................................................................................................................165
 ........................................................................................................ 167
................................................................................................................................167
 ...........................................................................................................................168
 .................................................................................................................168
 ......................................................................................................... 169
................................................................................................................................169
 ...........................................................................................................................169
 .................................................................................................................169
 ......................................................................................................... 170
................................................................................................................................170
 ...........................................................................................................................170
 .................................................................................................................171
 .................................................................................................................. 171
................................................................................................................................171
 ...........................................................................................................................171
 .................................................................................................................171
 ......................................................................................................... 172
................................................................................................................................172
 ...........................................................................................................................172
 .................................................................................................................172
 ................................................................................... 172
..............................................................................................................................172
 ...............................................................................................................173
 ............................................................................................................ 173
..............................................................................................................................173
 .........................................................................................................................174
 ...............................................................................................................175
 ................................................................................................................... 176
 ................................................................................................................................. 176
 ............................................................................ 177
 ............................ 177
a DAO ...................................................................................................................177
 ................................................................................................179
 ...... 184
 .................................................................................. 198

i


  y quanh  
  cao. Tài 
dành khi  . 
 h

t
 
 
   
 
 trình bày 
 g 
 
ái n
 
ý 



, c
 th và c.



hành vi. hình  

mô hình hóa .

 


ng 5: Mô hình thành phn vi EJB
Gii thiu khung J2EE và EJB, các khái nim v thành phng runtime ca
nó. N các kiu cu EJB, kt ni vic trin khai ca chúng, gii
thia các phiên bn EJB phân bit gia li gng b không
ng b. N  cp ng dn t   xây dng, trin khai s dng

ii
thành phn EJB.

Gii thiu khung .NET, các khái nim chung ca các thành phn .NET, các kiu thành phn
.NET, kt ni gia các thành phn, cách trin khai chúng, các thành phn cc b phân
tán, phân bit các thành phn kt ni và hp, gng b ng b. Ni
 ng dn t xây dng, trin khai, và s dng các thành phn
.NET.



 các 
C
 
ý 

C
 
 ý 

C
 
toán. ý  


 trình y hai Case Study a   khác

  
-Cô trong Khoa CNTT -
ý   
 sinh viên chuyên ngành Công
   xem tài
  
 
 ,  



1
: 

 

 khác
1.1  
 cùng d liu và tài liu liên quan  

nói  
 cùng nhau  
   phn cng  
  
khác v 
 
  

1.1.1   là gì?


 

 
 . Nó liên
quan   m  trong   
 [18]:
 phc tp bn cht vn có ca mt h phn mm. Nó t l vi kích c ca h thng,
s ng thành phn cu thành h thng, kích c cu trúc bên trong ca mi thành phn,
s ng và tính cht ph thuc nhau gia các thành phn.
 hiu mt cách trtính cht
ph thuy ví d t nhng khái nim ca lp trình ng. Kích c
ca mt phn mm ng th  dòng ngun, s lp, s 
hay s gói; cu trúc bên trong và ph thuc th hin cu trúc ca các lp, gói quan
h gia các lp, gói.
1.1.2 
Trong k thut phn mm truyn thng, mi kiu tác v thc thi bi h thng c nh
bi mt hay tp các thành phn liên quan nhau. u này xut phát t nhý n

2
v phát trin phn mm da vào các khái nim: trng hóa, un hóa, tách các chc
, li. ràng rng mt h phn mm vi s ng thành phn l
phc ti h có s ng thành ph
Tho gi phc tp phn mm thì ch cn ti thiu hóa s thành phn trong h
th gim s thành phn chúng ta ch cn phi gp nhiu ch vào trong
mt thành phn. Tuy nhiên, vic gim s thành phn trong h thm bo r
phc tp s thu này th thêm s phc tp ca mi thành phn riêng
l. Nói cách khác, mt h thng c cu to bi các thành phn l phc t
c cu to bi các thành phn nh a, nhiu nghiên cu ch ra r phc
tp ca h phn mm còn lin c a các thành phu trúc
bên trong và hành vi ca riêng các thành ph18].
 phc tp phn mm c xem v n cn phc gii quyt khc
phc bi các công c o ra phn mm. Nhiu nghiên c ra rng cht
ng ca các sn phm phn mm ti d án phn mm ph thuc rt nhiu vào
 phc tp phn mm. Tuy nhiên, n nay  mt gii pháp nào thc s hiu qu
 loi b  phc tp ho su chng phn mu
nhi phát trin th làm c gim thiu hoc loi bt tính phc t
thôi.
hóa c xem nguyên t c s n trong thit k phn
mm và th làm gim thiqun lý c  phc tp.  phc tp trong
cu trúc x lý th c tính toán da vào s liên kt ca các thành phn trong mt h
thu mt h thng hoc mt tin trình càng bao gm nhiu thành phn kt ni
nhau theo nhiu kiu c phc tp ca h thng các ti
càng lt ni s tr thành ph thuc ln nhau.
d, trong mt cu trúc phn mm, thành phn B gi ph thuc vào thành phn A,
nu si thành phn A thì thành ph b ng theo. Vì vy, cn phi sa
i thành phi thành ph hoàn thin sn phm không gây
li.  nu i thành phi thành phng
hp hai thành phn y ph thuc ln nhau tc thành phn A ph thuc vào thành phn B
thành ph thuc vào thành phn A thì s i ca mt trong hai thành
phn y s dn mt vòng lp su y d hiu khi chnh s
phi chnh sa B vic chnh sa B li dn vic phi chnh sa A quá trình này c
lp li.
1.1.3 


nh và phân tích yêu cu
Phát tho giao dii dùng
Thit k kin trúc
Thit k chi tit
To mã ngun

3
Tích h

giao d    


Mý 
thông tin. t  m
sao 
    
(architectural pattern),    (design pattern),   (component)  
. Tuy nhiên, v

chính xác   
 và
 các   
   bàn úc
.  còn l
 .
1.2 
 
1

 em xét, nghiên
trong công ngh 
          
   vai
 ý 
 
 các hình
  chính
này là  
 hay  .

  .

  
 [18]  hóa 

.
1
http://homepages.cs.ncl.ac.uk/brian.randell/NATO/nato1968.PDF

4


 
ý.
Quá trình này nh ng
    
, 
[13]:
Booch    
 : L 
; Xác   
thành   .
 
sau: v
                 
...

t
                 
 
ca vào 
 
     trong  
ý 
. K     

  .
S:
Kin trúc cn th hic cu trúc (structure) ca h thn giu các chi
tit.
Kin trúc phi hin thc hóa c tt c các ca s dng và kch bn.
Kin trúc phi th hic s n các yêu cu ca các bên liên quan.
Kin trúc phng c yêu cu v chn yêu cu v phi ch
1.3 
Trong ,  bàn 
 trình bày 
ý 
cho trình bày sau.

5
1.3.1 
Theo Taylor [18] k  
  . 
   quy (design
decision) là tru   
. S   :
C 
 trúc   
 (funý 
  
ng tác (interaction).  thành
 báo,  
trong java.
 (nonfunctional properties)
ng cách
ý.
  
 Swing hay JSP.

              

1.3.2 Thành ph
Các   bao  
 liên   khác nhau:
ý  hay hành vi
: l 
: 
ý bên 
 (software component). Theo Taylor [18]:
Tói 
 
tùy mà nó 
N 
Tùy theo 
  
   Thành
 c nguyên  (encapsulation), 

6
 (abstraction) dun hóa     N, các
ý có .
Tuy  
, thùng 
 
1.3.3 
   
 trong 
 

thân các 
 
 trê
 hay g. Ct 

giúp tra 
 
nh toán cho bên
 
chung. 

 theo  

. D
 [18]:
: 
:   kích

: SQL
:   

:    
 riêng-server 
CORBA, FTP, SOAP.
rung gian: 
           
trung gian 

7
  hích nghi:      
  

: 
 
 cách rong tính toán
, k 

  
  hình
client-    b :            

1.3.4 
   
 
 
.


1.3.5 
 
   
 
  phân tán,  
   :
Tách  ý: các thà
ày cho phép  
ý 


 i 

1.3.6 
 . Chúng 

 (architectural pattern) cung 
  

8
  

, 









: -t 
, ..
  ..Các 
ý
(Hình 1.1).

9
Hình 1.1 [18]

 
 
ý 

trung gian 

ý  ý  


10
(data) 

song song.
Tý là    
 -
-      
hay     
1.3.7 Mô hình 
     (architectural
mý 
 ý 

ý hi
nhau (Hình 1.1). 
1.4 

 

 
  
 
sau.

1. 
gói hay .   
này. 
http://worldcomp-proceedings.com/proc/p2015/SER6097.pdf
2. eBay
.  
3. Hãy t
4.   y
trình bày 
5.  .
6. úc
7.  . 



11
8. DAO  

9. 
10.    


12
C: 
 t 

Các nguyên l 

2.1 
P
  - 

(Unified Process)  
   
khi em nh 
  thêm 
c thô n   ([1][3]):
1.  
2.  
3. 
4. 


  
ràng, quá trình phân
  



  thông
g.


  


  
 


13
 
 trúc.
 
 không thành công 
  khách hàng  
 .  
 
  
tránh cái  
ra 
2.1.2  
 các 
 
         

 trong C hay Java 












 

2.1.3 
t 




 

14


mà sau này 
,  

 
2.1.4 

. 


  

 
2.2 
           
 
 
 






hay nhóm   khác nhau.  
(Hình 2.1)   tiêu khác nhau [8]:
   (presentation layer)         

 (service layer)
   (business layer)          

 (data layer)

T  (cross cutting)

15
Hình 2.1 [8]




.
2.2.2 Ný  
 

 c]:
Nguyên lý phân các : Phân chia  sao cho 
  các 
        cao (high cohesion)    (low
coupli ý 
dính  dù các  
ý  ành 
 hay  có liên t nhau.

16
Nguyên lý   

Nguyên lý k  ý 

 .
Nguyên lý c ý 
 
 

ng 
ý  quan tâm khác nhau.


ý giao
 

2.3 
 
ý 
trúc,  
trúc 
trúc  g
  khác nhau. 

khác nhau.  chính 



 

Client/Server, N--



, , 
2.3.1  Client/Server
                
khách c 
-
tiers). 
 
 trên ent
 

17

  thông tin cho client.
Ngày nay,   client/server  : C  
 Microsoft Windows - 
 
ngân  -mail, FTP khách hàng và các công 

  
Các h i-client: Cách tip cn này cho phép client giao tip vi client khác
thông qua mi da trên server. Client có th c d liu t server gi d
lin mt server s dng m  d liu này cho phép
client phân phng b hóa các tc gi
mt kin i th ng.
H Peer-to-c phát trin t kiu h i - client. Kiu P2P cho phép
i vai trò ca chúng trong quá trình phân phng b các
file và thông tin thông qua nhiu client. Kin trúc này m rng kiu client/server thông
qua vic nhiu phn hi cho các yêu cu, chia s d liu, khai thác tài nguyên,
kh c h loi b các bên.
ng dng server: mt kiu kic bit trong  thc hin
các ng dng dch v mt client truy cp thông qua mt trình duyt hoc mt
c t phn mc bit. d t client thc hin mt ng dng
chy trên server thông qua nn tdch v u cui.
   client/server
tính bo mt cao: Tt c d ling s qun lí, an
toàn .
Truy cp d liu tp trung: Bi d liu ch  trên server nên vic truy
cp và cp nht d liu s ni quyi qun tr.
D dàng bo trì: Vai trò và trách nhim ca mt h thc phân b trong
mt s c bin vi nhau thông qua mt mm bo cho
các máy client không b ng khi mt máy server b sa cha, nâng cp hoc di
chuyn.
Tuy nhiên, kiu ki mt s bt tic xây dng ng dng có
d liu logic nghip v c kt hp cht ch u này th tác
ng tiêu cn vic m rng h thng d n s ph thuc vào mt server
trung tâm,  tin cy ca h th gii quyt nhng v y,
kiu kin trúc client-n thành kiu kin trúc 3-tng (hoc N-tng) sau
này.

Trong quá trình  chúng ta   
  , 

18
ý 

serve
 


ào thành 
phân  
 qua   
 
  :
Kh   s dng: các thành ph  c thit k  tái s dng trong
nhng hoàn cnh khác nhau vi nhng ng dng khác nhau. Tuy nhiên có mt
s thành phn có th ch c thit k  làm mt công vic c th.
Kh  c: Các thành phn th c thay th bng các thành phn
.
Không hoàn cnh c th: Các thành phn hoi nhng hoàn cnh môi
ng khác nhau. Các thông tin c th   liu tr c chuyn v
thành phc bao gm hoc truy cp bi thành phn này.
Kh  rng: mt thành phn th c m rng t mt thành ph
cung cp thêm các trng thái và hong mi.
 Thành phn tip xúc vi giao dii gi s dng chc
a không tit l chi tit v tin trình ni b hoc bt k mt bin hoc
trng thái ni b.
c lp: c thành phc thit k ch ph thuc ti thiu vào các thành
phn có th c trin khai trong bt k ng thích
hp mà không n các thành phn hoc các h thng khác.

   ;    thành

,
không ;   
  

 
cho chúng 
COM thành ph; CORBA hay EJB trong J2EE 




19
Tuy nhiên, các trong 
 .NET 


  rúc 

D trin khai: Các phiên bn nên có th thay th phiên bn hin ti
không n các thành phn khác hoc h thng nói chung.
Chi phí gim: Vic s dng các thành phn ca bên th ba cho phép dàn tri chi phí
phát trin và bo trì.
D dàng phát trin: Các thành phn thc hin c giao din ni ting cung cp chc
nh nên cho phép phát trin mà không ng các b phn khác
ca h thng.
Tái s dng: Vic s dng các thành phn tái s d c
s d  gim chi phí phát trin chi phí bo trì qua nhiu ng dng hoc h
thng.
Gim thiu s phc tp k thut: Thành phn gim thiu s phc tp thông qua vic
s dng vt cha thành phn dch v ca nó. Dch v thành phn bao gm kích
hot thành phn, c xp hàng, các s kin, và các giao dch.

 
  


này khi 
.
 
 trên các
ho, hành vi quan 
 
. Mô 
 hóa các .
, chúng ta khá 
 mình   liên
quan trong nghi
  
 nên  khi 
  . Tuy nhiên, trong  nhóm 

20
       

 mô hìn
 còn 
 
do   hình  
 
  
 
, chúng ta 
cách phân 
 cho chi phí cao.    
  
 
N  
Truyn thông liên lc: Tt c các thành viên trong các nhóm phát trin th s dng
hình mic  truyt kin thc nghip v vi
mt ngôn ng nghip v ng mà không cn các thut ng k thut.
M rng: hình ming các -t, d dàng cp nht
m rng khi u kin và yêu ci.
Kim chng: ng hình min gn kt nhau mt cách lng lo nên chúng
d dàng c kinh.

 
 
 
 
 
.
2.3.4 
  tro
    
nhau  và t rõ ràng và
hân    
tính  sau này.  
   
óa     nghiêm ng
  
thành  

21
 ác y tính 
các  
 
  n giao
   liên quan
    bao

Trng: Kin trúc phân tng th hin cái nhìn toàn b h thng ng th
cung cp y  chi ti hic vai trò và trách nhim ca các tng riêng bit
mi quan h gia chúng.
 Không cn ph nh v c loi d lithc thuc
tính, hoc thc thi trong quá trình thit kc tip xúc
ranh gii tng.
nh ràng các tng ch Vic tách bit chi tng
ràng. Tng trên cùng ng trình din gi ln ti, chng h
các tng nghip v và d liu, và có th x các s kin trong các tng, cho phép d
liu chuyn lên và xung gia các tng.
Kt dính cao: Kin trúc y xnh ranh gii trách nhim cho tng tng m
bo rng mi tng chc tin nhim v ca t
s giúp t gn kt bên trong tng.
Tái s dng: Tng th thuc vào tng kh
 tái s dng trong các tình hung khác.
Kt ni lng lo: Vic liên lc thông tin gia các tng da trên khái nim trng
và các s ki cung cp kt ni lng lo gia các tng.
các hàng, các
  web, 
M  mô hình MVC có 3 vai trò mô hình
(Model), Khung nhìn (View) Controller). hình 
hình ng; Khung nhìn 
dùng và   
Da trên s kin: c s d cung cp thông báo
cho View khi d lii bi Controller.
Phân cp x s kin: B u khin x các s kin nhc t giao diu
khin trong các View.
     
        
 này cho 
. thành
 cách này cu  .
N  mô hình 

22
Trng: phân tng cho phép các c thc hin m trng ca
các tng.
lp: cho phép nâng cp công ngh  lp các tng riêng bit nhm gim thiu
ri ro và gim thin toàn b h thng.
Qun lý: tách mi quan tâm cnh ph thuc, và t chc tt mã ngun.
Hiu sut: phân phi các lp trên nhiu tng vt lý có th ci thin kh  rng,
kh u li, nâng cao hiu sut ng vai trò tái s dng. d, trong
ng th c tái s di nhng lc khác
 cung cp mt vai trò c th hoc mi dùng tùy chnh trên cùng
mt d liu và ch
D kim th: kh m th ng nh giao din nh gia các
t y dng gi bc các hành vi ca
ng c th u khin...

K chúng ta  
khi chúng ta  thì áp
 cho các nhóm 
   
  
 

  
 qua  . 
 thông qua t
  
 hình ý 
 . g các 
 

Giao tip p: Tt c các giao tip gia các ng dc da trên các
c bi.
X lý logic phc tp: Các lnh phc tp th c thc hin bng cách kt hp
nhiu lnh nh  mi lnh nh x lý mt công vic c th.
Chnh sa cho x lý logic: Ba bus da trê câu
lnh chung nên th thêm hoc bt ng d c
s d x lý p.
Kt hp nhing khác nhau: Do vic s dng hình giao tip da trên
p theo mt chun chung nên các ng dng th i nhau trong
nh

23
 ý . 
nên cho phép chúng ta  vào trong
ý  
 us  
ESB (Enterprise Service Bus): Da trên thit k MS, kiu ESB s dng dch v cho
truyn thông gia bus và các thành phc gn vi ng cung cp dch
v chuyp t nh dnh dng khác. ng thi cho phép
client s dnh d giao tip vi nhau.
ISB (Internet Service Bus ESB i ng dng máy ch trong
mi thay trong mt mngng ct lõi ca ISB s dng URI các
 u khin dò tìm ng dng và dch v trong mi.

Kh  rng: Các ng dng th c thêm vào hoc b
không y n các ng dng khác. Nhing hp ca cùng mt ng
dng có th c g x lý nhiu yêu cu cùng mt lúc.
Ít phc t phc tp ca các ng dng s gii ng dng ch cn bit
cách giao tip vi bus mà thôi.
Linh hot: vic gp các ng dng khin cho vic x lý ít phc tc các
hình truyn thông gia các ng dng có th i d  c s thay
i trong nghip v hoc yêu ci dùng. Nhi y dn ti
trong cu hình hoc tham s cho nhng yu t u khin quá trình dò tìm.
Kt ni lng: min là các ng dng tip xúc vi mt giao din phù hp da trên thông
báo ca thông tin liên lc vi các bus. Do không có s ph thuc vào các ng dng c
th nên i, cp nht, và thay th vi hin th cùng mt giao din.
ng dn: vic thc hin bus gim tính phc t h tng, mi ng
dng cn h tr ch mt kt ni duy nht vi bus thông báo thay nhiu kt ni
cho các ng dng khác.

K bus  
 
 trúc  

.
2.3.6 -
N- 3-t k  
 theo , 
 N- 
ng thành các 



24
ch-
n+1 

-t   
  
 
à.
 - 
 c 
t tr 
 các  trình  ai trên các y khách
  
 -
Bo trì: Bi mi tc lp vi các lp khác, nên cp nht hoi không
n các ng dt toàn th.
Kh  rng: các tng c da trên vic trin khai tip ti nên
nhân rng ra mt ng dng là n .
Tính linh hot: Bi mi tng th c qun lý hoc thu nh mc lp,
nên tính linh ho
Sn sàng: Các ng dng có th khai thác kin trúc mô-a h thng nên cho phép
m rng các thành phn d dàng và n sàng.
K- hay 3-   
  
 trình  
   N-t 3-t 
chúng ta    
 
K  
 
    trên 
 logic



 . 
               
húng gi
 
khác. 

25
Trng: u này cho phép chúng ta gi phc tp ca hành ng vn gi
n ca hành ng. d, mt giao din trng th h
tr các hong truy cp d liu bng cách s dget()
set().
Thành phn: ng th c lp ráp t ng khác, th ch
ng ni b t các lp khác hoc tip xúc vi chúng thông qua giao din.
K tha: ng th k tha t ng khác s dng ch
n ho thc hin hành vi ma, k tha
làm cho bo trì và cp nht d  c truyn
t ng k tha.
   ng tip xúc v  ng khác ch     c,
thuc tính, các s kin, n các chi tit ni b n t ng khác
và tru này làm cho nó d dàng cp nht hoc thay th ng, min
là giao di không ng và mã khác.
 K thut này cho phép h vi ca lp  bng cách thc hin
hành vi mi cho ng hin ti.
Tách bit: ng th c tách bit t i dùng bt
giao din trng c th i dùng có th hic.
  
  
 
  liên  
nên làm cho 
 
 cách 
 

 cao: 
   t   
nhau và   dính cao.

  i
phù  
 gói logic và
 các  
t.

26
2.3.8 n trú
 các 
 
  .

trên m  

ao
 
 .

Dch v t tr: Mi dch v c duy trì, phát trin, trin khai c lp vi phiên
bn. Dch v th t bt c  ng, ta c t xa,
min là mng h tr các giao thc truyn thông cn thit.
Dch v liên kt lng lo: Mi dch v c lp vi dch v khác và th c thay
th hoc cp nht không vi phm các ng dng s dng min giao din
vg thích.
Kh da trên chính sách: ng h
các  tip, giao thc và an ninh.

trì 
 

Liên kt min: Tái s dng các dch v ph bin vi giao din chui
kinh doanh và gim chi phí.
Trng: Dch v hoàn toàn t tr truy cp thông qua mt hng chính thc,
cung cp kt ni lng lo và trng.
Kh m: Dch v th cho phép các ng dng các dch v khác xác
nh v trí ca nó và t ng gi.
Kh    Bi các giao th  nh dng d liu da trên các tiêu
chun, nên các server và client ca các dch vth c xây dng và trin khai trên
nhng nn tng khác nhau.
Hp hóa: Dch v th cung cp nhng ch th, ch không phi sao
chép các ch các ng dng.

 
   có th
  
  

27
 trên tính toán  khi
chúng ta  hay  
;  khi   



 ý 
 trúc có ý 




1. 
2. 
https://arxiv.org/ftp/arxiv/papers/1610/1610.09240.pdf
3. 
http://www.service-architecture.com/articles/web-
services/enterprise_service_bus_esb.html
4.  (cohesion),  dính (coupling) 
  
5.  ý 

6.  
7. Các  J2EE 
http://www.softwaresecretweapons.com/jspwiki/resources/presentations/Sun_eBay6-
2_forWeb.pdfhttp://www.slideshare.net/tcng3716/ebay-architecture
8.  mây (cloud) 
https://media.amazonwebservices.com/AWS_Cloud_Best_Practices.pdf
9. 
https://media.amazonwebservices.com/AWS_Cloud_Best_Practices.pdf
10. 
http://www.ece.ubc.ca/~matei/EECE417/ebay.pdf
11. 
https://www.infoq.com/presentations/service-arch-scale-google-ebay

28
C: 

ý


2


 

mô hình 


3.1 

hình 
hình hóa
ày  
ý 
3.1.1 





eo


  hóa 
 

 
ý  phù

 
2
http://www.mrtc.mdh.se/han/FoPlan/ass2-bjornander.pdf

29

 
hbên ngoài 
 
 
 
 


 







 






3.1.2  và mô hình hóa
Nh 






  sau này.

 sau này.


ý 

30






hay 



 

init()     


 





               


3.1.3  


 Khía



 ý 







31



 
  
 
 
- 
 

 

ý ý 



Tính  và rõ ràng

 


 
: 

ác cách



  
 




3.1.4 
Các mô hì 

hông


32




Khung nhìn
Khung nhìn 
 (viewpoint) là c 
 .
 
 cách  cho các
  
 Hình 3.1a khung -
Server 3.1b khung 
hai khung       Các quan
  

Qu 


 ý 

 (deployment vie
ý.
 (process  ý 

  

33
Hình 3.1: Khung :
-
m và khung nhý 
             

 nhu c
liên quan.

nhau.
3.1.5  nhìn
 cho nên  thông tin liên quan 
  khác nhau.  
khung nhìn không  hai khung nhìn A B u
 

  


khung 
 khung



34
3.2 

 ý c

- ?
- 
- 


 chúng ta không nên quá
 

3
:
         Architecture Analysis & Design
Langua
ý
            Based
Language and Environment) ngôn 


 AADL.
Darwin
  

Wright.

  
khác).
 các





 
3
http://www.mrtc.mdh.se/han/FoPlan/ass2-bjornander.pdf

35
TASM (TASM: Timed Abstract State Machine) 

             
.
3.2.2   
 
t mô hình [18].
1  hình



1




2



3



4



5




6

Cách 
7


nào
8
ng


9


10

            
khung           
hình.
3.3 

L (Uniý 
  
 ý               
 


.


 cao trong
 
 các

36
 

 
   Tính toán      . Tuy
nhiên, 








Hình 3.2



  

  .
 
  

3.3.2 
   khung nhìn khác nhau 
khung              
khung nhìn. Trong UML, khung nhìn 

Khung  (Use case view)
   
<<import>>
Tính toán
Tính toán
Tính toán


<<call>>
(a)
(b)

37
 


trúc.
Khung nhìn logic (Logical view)      

 .
Khung  (Process view)



 
Khung nhìn  (Development view): Khung nhìn n 
 

 
Khung nhìn  (Physical view)


 
này.
:
 

ý (Physical architecture)
.

 nào
18]:

ý.

theo 
 theo 
 
ý nó.



38
  
 


            
 



 k
ý.
3.3.3 
 bao hàm logi không  ý 
 

 nhó  
  . Sau

C?

C
  nhau  các 
 gây 
  


 
.


gói, thành ph

trong Hình 3.3.

39
Hình 3.3





40
gói  
nhau
 nhóm theo gói. Thành
 
private 

 
 
 M

ý 

              

 


Hình 3.4

  

 
ý 
 .


   
  


  
nhau.
<<component>>


41
:   


rong các Ch-10.
ý
ý 
cách chúng

ý các 

n


Các file nhau  
i?
 ý ký 
 trong
UML 


ý 
ý 

ý ý 




 
 

nó.      n         


rìn


42

 ý:


: Bý  


.

 trình bày m
i dung 
các quan
 
ng này 

1. , 
.
2. 
3. 
4.              
https://www.cs.ubc.ca/~gregor/teaching/papers/4+1view-architecture.pdf
5. 
6.   liên  ý .
7. ki

http://www.slideshare.net/tcng3716/ebay-architecture
8. 

9.  n

10. ý bán
sách online
C
43
: 

 



4.1 
4.1.1 
Trong l     (OOP: Object-Oriented Programming), c g trình
   
  . Các ngôn
ã   int,  char
    . , 

     (COP: Component-Oriented Programming) cho phép các
 ây
 
 này c mua hay 
  
  .
, COP 
  C
 
  . 
  công  .
  
 . Nói n
  naynày 
các n  

Tuy nhiên, trong  ch là t
n   
 tên .  

  
 
n  M
C
44
 cuàng ngày càng
 
 

 
 
(1 exabyte = 1 gabytes) thôn  
 .
COP     ách
  . , nh ngân sác
 thay      

   
.
  
   . do c
 

 
Si
S   
làm   N
:
Sao chép     trong
C d n 
 k  
này  hàm/ 
  
   
 s   
  chúng.

, ,  
    s
.  
g                 
  
.  xem  
 
C
45
4.1.2 
    
 tr 
...   
 

   
  
  ách 
    thành
[8]:
(1)   
. Nó .
(2)                
p thông qua các giao
 .
(3)   ng

 .
(4)    
  s
  .
 xem 
  các  nh
.
   xác
.  
  
              , EJB
(Enterprise Java Beans)  Sun Microsystems, COM (Component Object Model), DCOM
(Distributed Component Object Model), các thành ph 
CORBA (Common Object     nhóm Object Management
Group.
C
46
4.2 
 
  
  

 
   

ho th 
 
- 
- 
- 

- Nguyên 

- 
-down.
 t : Không nên 
liên quan vào trong   

         


.
 
 

 xun 




  
 

 .
C
47

     
 
             

 
ít lo 
 
: 
 

- 
- 
 





  
 


 
  



Fa 


bên ngoài 
Các t n
  


 
 
C
48
-  


   

quan  Hi
nay               
https://eclipse.org/jwt/
-               
  
hàng. 






      


   
thành thành ph



ngoài, 

 
               
Thành p 

               





C
49
4 
Không  t
khác nhau do cluôn     

.
 C 
  
. V 
  framework) 
ba mô hình:
M:   khi nào là 
trong 

.
 i xác  
ch 

: Mcách 
còn  hay 
  
 , EJB 
Microsystems, COM (Component Object Model) DCOM   
Microsoft CORBA (      OMG (Object
Management Group).
           ng các t    
Windows. h   cho phép

   
l    

  các
   trên  
C    
(Object Request Broker)   các
hác nhau. Các i


 
(IDEK (Bean Development Kit) 
C
50
    ng cho Java          s.
Microsoft .NET 

 bao 


nên 
  
 
               


  
ch hóa 
.
4.4   
 ô
trình bày  này trong UML 

4.4.1 Mô hình 
  t  
  trúc logic các
fil :
Sn phm ngun: mt sn ph thi gian biên dng là mt
file mã ngun cha mt hoc nhiu lp.
Sn phm thc thi: mc thi c, liên kt các thành phn nh
phân trong thi gian chy dng  hong. Mt thành phn thi din cho
 thc u hành bi mt b xý hay máy tính.
ng c s dng  m rng a sn phng vi công ngh.
d vi mt profile EJB trong J2EE th t loi <<executable>> vi
<<EJB>>.
Trong UML m             nhãn


                
    

            artifact    

C
51
 S

 h

k
artifact 
ình 4.7 

Hình 4.1: Kt hp khi thành phn thc thi [21]
Trong Hình 4.7 thành phc hiu này
 thng có mt thành phn tên là Titlempl. <<artifact>> là file tên Title.jar.
ng là file chn.
4.4.2 
 
ó   




Nút: nhng tài nguyên tính toán nhng sn phc tri thc hin.
Các tài nguyên y bao gm các thit b t b 
gm các nút con trong nhng thit b a (container) c
d lit nút có kiu và th hin cc biu din bi hình l
chiu vi tên bên trong nó. Ging, mt th hic gch chân. Khi
c s d biu dic gán nhãn.

 n
 

 
C
52
        

 

 



             cho trên Hình 4.8.
J2EEServer <<execution environment>>, DBServer <<execution environment>>. Artifact
file ShoppingCartApp.ear các artifact con các file ShoppingCart.jar
Order.jar application.xml file ejb-jar.xml
                 
<<deployment spec>>.
Hình 4.2u 
4.5 
           
  

  
hai : 
C
53

1.  và t
2.   hai nguyên lý t           
http://www.jasoncoffin.com/cohesion-and-coupling-principles-of-orthogonal-object-
oriented-programming
3.                 
http://www.codeproject.com/Articles/845616/Cohesion-and-coupling-Principles-of-
orthogonal-sca
4.                  
http://www.academypublisher.com/jcp/vol04/no09/jcp0409797805.pdf
http://www.irisa.fr/lande/lande/icse-proceedings/msr/p18.pdf
5. t 
https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
http://www.davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html
http://www.c-sharpcorner.com/UploadFile/damubetha/solid-principles-in-C-Sharp/
6.           

7.  
lái.
8.  khách hàng mua sách
online
9. 
10. 
11. mua y
bay
C
54
: HÌNH EJB
 là trình bày:
J2EE và kin trúc EJB
Các khái nim v thành phn EJB ng chy ca nó
Các kiu thành phn, kt ni và vic trin khai EJB
Gii thiu các tíni ca EJB 3.0
Hng dn xây dng, trin khai và s dng thành phn EJB
5
5
 98. EJB 2.1
   
.
 i 
n Anywhere); 
         J2EE, Struts   
ông n 
khác   . 
 
JSP, JSF và Strong 
  
. 

  


         
 phía client
 

   EJB         
 J2EE.

   EJB 3.0 và EJB 2.x.
5.1.2. J2EE Server
J2EE server  
JNDI (Java Naming and Directory In terface) API cho phép các client tìm kim và xác
nh v trí container cha các thành phn .
C
55
J2EE h tr vic xác thc và an toàn.
J2EE h tr dch v HTTP và các dch v n EJB, các dch v 
Hình 5.1: 
5.1.3. Container
  EJB Container 
 )  EJB
:
 và an toàn (transaction, security)ao  và
an toàn   phân tán.
 (persistence) entity bean)

 (life cycle) 
.
Hình 5.2: EJB container [21]
EJB contain  EJB 
  
container. C  c client
   an toàn 
ên EJB.
Hình 5  
  các thông tin   EJB container
trác, 
. 
 EJB, 
 và t.
C
56
5.1.4. EJB
  
      th           
enterprise bean khác trên cùng .  
 
 mô t Deployment Descriptor) 
5.2. MÔ HÌNH N 
5  EJB 2.x
  

 
    giao di      interface    
enterprise  .  

 EJB và quá trình  .
Hình 5.3: thà EJB
   giao
 cthành
 cách  EJB

 EJB  EJB y trên server

 nó.
Các Enterprise  

 theo  EJB. bean sau:
Stateless session bean) 
 
 
C
57
WSDL
  
các  

Bean phiên  (Stateful session bean) 
bean  

bean 
 bean phiên nào c c
 ch bean :
MDB (message driven bean) là bean  
 EJB 
  trong Java.
BMP (Bean Managed Persistence) các entity bean) trong 

CMP (Container Managed Persistence) c bean  
                 
container. Tuy nhiên, các bean  
 bean  
EJB n javax.ejb.EJBObject sau giao
 java.rmi.Remote         EJB    
javax.ejb.EJBHomejava.rmi.remote.  
javax.ejb.EJBLocalObject javax.ejb.EJBLocalHome. 
   
  xa.   
c các
 
 t.
5.2.2. EJB 3.0
   

 
 
khai.

 .
Không       bean phiên. Giao      bean
phiên              
EJBObject, EJBLocalObject,  java.rmi.Remote.
C
58
  phiên. bean 
a hình.
. 
.
5.2.3 Bean phiên
bean phiên (sesion bean) ong Server 
 bean phiên.
  , các bean phiên 
 này trên server. Bean phiên  cho client
khi client k
bean phiên :
Bean phiên trng thái: Trng thái ca mng là b giá tr ca các bin. Trong
mt bean phiên trng thái, các giá tr biu din trng thái ca mng duy
nht m       ng vi nó, nên trng thái này
c gi trthoi. Trc duy trì trong sut phiên
làm vic gia client và bean. Nu client loi b bean hoc ngt, phiên kt thúc các
trng thái s mt.
Bean phiên phi trng thái: Bean này không duy trì tri vi client.
Khi mt client gi mt c ca mt bean phi trng thái, các bin ca bean
th cha mt trng thái c th cho m trong thi gian thc hin cuc
gc hoàn thành, trng thái này s b mt. Tuy nhiên, các client có th
i trng thái ca các bean gi cho li gi tip theo. bean phi trng thái
th h tr cho nhiu client, nên chúng linh hot ng di s client
ln. Bean hiên phi trng thái th t dch v ng thái
thì không.
Bean phiên  nht: c khi to mt ln tn ti sui mt
ng dngc thit k  dùng chung truy nhp bi nhiu client. Khác
vi bean phi trng thái, ch có mt b nht cho mi ng dng và bean này
 t dch v web.
5.1: ean   

//remote interface: Converter
package converter.ejb;
import javax.ejb.Remote;
@Remote
public interface Converter {
public double cToF(double c);
public double fToC(double f);
C
59
}
//stateless session bean: ConverterBean
package converter.ejb;
import javax.ejb.Stateless;
@Stateless
public class ConverterBean implements Converter {
@Override
public double cToF(double c) {
return c * 9/5 + 32;
}
@Override
public double fToC(double f) {
return (f - 32) * 5/9;
}
}
5.2.4.  EJB
 client 
-
bean . Web servSOAP, HTTP,
WSDL  client () 
nào  cài
g thái, JAX WS Tính linh
.
client 
 
client .    
.
: 
Package ejb.service;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
@Stateless
@WebService
public class HelloServiceBean {
private String message = "Hello, ";
public void HelloServiceBean() {
}
@WebMethod
C
60
public String sayHello(String name) {
return message + name + ".";
}
}
5.2.5 Bean 
Mentity bean   
Sinh viên, Gi các Kh bean
 bean  
  
 EJB qua container   các
clien.  

 5.3:  : BMP (entity bean Bean Managed Persistence)
CMP (Container Managed Persistence). bean  BMP sinh
viên Stu
CREATE TABLE student(id VARCHAR(3) CONSTRAINT pk_student PRIMARY
KEY,gpa Number(2,1));
//The following is the home interface for this student BMP
//entity bean.
import javax.ejb.*;
import java.util.*;
public interface StudentHome extends EJBHome {
public Student create(String id, double gpa) throws
RemoteException, CreateException;
public Account findByPrimaryKey(String id) throws
FinderException, RemoteException;
}
//The following code is the remote interface for this student //BMP
entity bean.
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Student extends EJBObject {
public double getGpa() throws RemoteException;
}
//The following is the BMP implementation entity bean where SQL
//statements are explicitly included.
import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
public class StudentEJB implements EntityBean {
private String id;
private double gpa;
private EntityContext context;
C
61
private Connection con;
private String dbName = "java:comp/env/jdbc/StudentDB";
public double getGpa() {
return gpa;
}
//The following ejb callback methods are executed by EJB
//container. The Detailed references are in this chapter
//reference.
//When a new bean instance is created the method ejbCreate()
// is automatically called by the container to insert a row in a
//corresponding table in the database.
public String ejbCreate(String id, double gpa) throws
CreateException {
try {
insertRow(id, gpa);
} catch (Exception ex) {
throw new EJBException("ejbCreate: ");
}
this.id = id;
this.gpa = gpa;
return id;
}
public String ejbFindByPrimaryKey(String primaryKey) throws
FinderException {
boolean result;
try {
result = selectByPrimaryKey(primaryKey);
} catch (Exception ex) {
throw new EJBException("ejbFindByPrimaryKey: ");
}
if (result) {
return primaryKey;
}
else {
throw new ObjectNotFoundException
("Row for id " + primaryKey + " not found.");
}
}
public void ejbRemove() {
try {
deleteRow(id);
} catch (Exception ex) {
throw new EJBException("ejbRemove: ");
}
}
public void setEntityContext(EntityContext context) {
this.context = context;
try {
makeConnection();
C
62
} catch (Exception ex) {
throw new EJBException("Failed to connect todatabase.”);
}
}
public void ejbActivate() {
id = (String)context.getPrimaryKey();
}
public void ejbPassivate() {
id = null;
}
public void ejbLoad() {
try {
loadRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: ");
}
}
public void ejbStore() {
try {
storeRow();
} catch (Exception ex) {
throw new EJBException("ejbLoad: " );
}
}
public void ejbPostCreate(String id, double gpa) { }
void makeConnection() throws NamingException, SQLException {
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup(dbName);
con = ds.getConnection();
}
//The following methods are callback methods to invoke SQL
//statements to access database
void insertRow (String id, double gpa) throws SQLException {
String insertStatement = "insert into student values(?,? )";
PreparedStatement prepStmt =
con.prepareStatement(insertStatement);
prepStmt.setString(1, id);
prepStmt.setDouble(2, gpa);
prepStmt.executeUpdate();
prepStmt.close();
}
void deleteRow(String id) throws SQLException {
String deleteStatement = "delete from student where id = ?";
PreparedStatement
prepStmt=con.prepareStatement(deleteStatement);
prepStmt.setString(1, id);
C
63
prepStmt.executeUpdate();
prepStmt.close();
}
boolean selectByPrimaryKey(String primaryKey) throws SQLException {
String selectStatement="select id "+"from student where id
=? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setString(1, primaryKey);
ResultSet rs = prepStmt.executeQuery();
boolean result = rs.next();
prepStmt.close();
return result;
}
void loadRow() throws SQLException {
String selectStatement = "select gpa " + "from student where
id = ? ";
PreparedStatement prepStmt =
con.prepareStatement(selectStatement);
prepStmt.setString(1, this.id);
ResultSet rs = prepStmt.executeQuery();
if (rs.next()) {
this.gpa = rs.getDouble(2);
prepStmt.close();
}
else {
prepStmt.close();
throw new NoSuchEntityException(id + " not found.");
}
}
void storeRow() throws SQLException {
String updateStatement = "update student set gpa = ? " + "where
id = ?";
PreparedStatement prepStmt =
con.prepareStatement(updateStatement);
prepStmt.setDouble(1, gpa);
prepStmt.setString(2, id);
int rowCount = prepStmt.executeUpdate();
prepStmt.close();
if (rowCount == 0) {
throw new EJBException("Store id " + id + " failed.");
}
}
}
5.4: istent
  
bean  Boo bean BookBean các

C
64
//EntityBean: BookEntity
package ejb.book;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
@Entity
@NamedQuery(name = "findAllBooks", query = "SELECT b FROM Book b")
public class BookEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String title;
private float price;
@Column(length = 2000)
private String description;
private String isbn;
private int nbOfPage;
private boolean illustrations;
public BookEntity() {
}
public BookEntity(Long id, String title, float price, String
description, String isbn, int nbOfPage, boolean illustrations) {
this.id = id;
this.title = title;
this.price = price;
this.description = description;
this.isbn = isbn;
this.nbOfPage = nbOfPage;
this.illustrations = illustrations;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
C
65
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isIllustrations() {
return illustrations;
}
public void setIllustrations(boolean illustrations) {
this.illustrations = illustrations;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getNbOfPage() {
return nbOfPage;
}
public void setNbOfPage(int nbOfPage) {
this.nbOfPage = nbOfPage;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
C
66
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id
fields are not set
if (!(object instanceof BookEntity)) {
return false;
}
BookEntity other = (BookEntity) object;
if ((this.id == null && other.id != null) || (this.id !=
null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.me.bookws.Book[id=" + id + "]";
}
}
//Remote Interface: BookRemote
package ejb.book;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface BookRemote {
void create(BookEntity book);
void edit(BookEntity book);
void remove(BookEntity book);
BookEntity find(Object id);
List<BookEntity> findAll();
List<BookEntity> findRange(int[] range);
int count();
}
//Stateless session bean: BookBean
package ejb.book;
C
67
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
@Stateless
public class BookBean implements BookRemote {
@PersistenceContext(unitName = "BookWSPU")
private EntityManager em;
public void create(BookEntity book) {
em.persist(book);
}
public void edit(BookEntity book) {
em.merge(book);
}
public void remove(BookEntity book) {
em.remove(em.merge(book));
}
public BookEntity find(Object id) {
return em.find(BookEntity.class, id);
}
public List<BookEntity> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(BookEntity.class));
return em.createQuery(cq).getResultList();
}
public List<BookEntity> findRange(int[] range) {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(BookEntity.class));
Query q = em.createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<BookEntity> rt = cq.from(BookEntity.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
C
68
5.2.6.  MDB (Message-Driven Beans)
 
 
JMS    
                 
enterprise bean khác,  
 x 

MDB --. MDB 
 
  n .  MDB
 sau:
 MDB 
JNDI
 MDB này

 

MDB  theo - các 
 
 x pMessageListener onMessage(). ây
 bean MDB  (TextMessage).
: Bean 
//MessageDrivenBean: SimpleMessageBean
package ejb.mdb;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.MessageListener;
import javax.jms.Message;
import javax.jms.TextMessage;
import javax.jms.JMSException;
import javax.annotation.Resource;
@MessageDriven(mappedName = "jms/Queue")
public class SimpleMessageBean implements MessageListener {
@Resource
private MessageDrivenContext mdc;
public SimpleMessageBean() {
}
@Override
public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage) {
C
69
msg = (TextMessage) inMessage;
System.out.println("MESSAGE BEAN: Message
received: " + msg.getText());
} else {
System.out.println(
"Message of wrong type: "
+ inMessage.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
}
5.3 
Trong   
xem xét các   thành  
 M t EJB
.
  
       thành      
trong  
 EJB thông qua
   EJB 
nh Web,  JavaBean,  thành
  
Hình 5bean phiên  hai bean   
Hình 5 bean phiên và bean  [8]
C
70
5.3.1 Kt hp các kt nng b
Mt li gng b thc thi u ng. Mt client gi mt
c t xa qua giao din cng thành phn EJB. Giao din che du tt c
vit chi tic logic nghip v cng thành
phn t thúc công vic, s ng các yêu cu bng vic gi tr kt qu hoc
có th yêu cu các dch v t các thành phn khác và ch phn h chuyn ti client.
Mt ví d n hình cho kiu truyn thông này là to gi hàng. Bean phiên s gi mt yêu
cu ti mt bean thc thch x . Khi mng thành phn client khi to mt yêu
cu, lung yêu ci n khi nhc phn hi t thành phn EJB 
Hu ht các ví d u hong ch  ng b.
5.3.2 Kt ni lng lo ng b
Mt truyng b gm truyn thông dp gia mt thành phn
EJB client ca nó. Mt client gi yêu cu ti mt thành phn  không t 
tip tc duy trì tin trình ca mình. hai hình thc truy  ng b:
Qup da vào i và qung bá da vào ý/công b.
Truyng b da trên mt i yêu cu, mp vi
h tr bi JMS gii nhn p hoi dùng p. Trong khi
i ý/công b ch   cho i cung cp gi
p vào mt hoc nhii dùng th nhp t ch 
này. Trong truyng bu kt ni lng lo nên dn
ng t
5.3.3 Truyn thông t xa và cc b
Mt thành phn client server ca th nm trên mt y hoc trên các máy o Java
khác nhau. Nu hai thành phn EJB chy trên cùng mty, s có chi phí thp  nhiu bi
s dng giao din cc b so vi s dng giao din t xa do ti sao EJB 2.x thêm các
giao din localHome localObject vào giao din t xa. Mt vài thc th bean th cung
cp c hai giao din trong EJB 2.x . Mt bean phiên th a bean thc th
mt bean thc th th  trc tip vi client hoc thông qua mt bean phiên hoc
c kt ni ti bean thc th khác. Mt giao din cc b cho phép tham chiu ti mt
c trong hình truyn tham chiu, trong khi mt giao din t xa thc hin
trong mô hình truyn tham tr.
5.3.4 Các tham chin các bean thc th
 n bean thc th , mt bean phiên phi trng thái phi tìm các thành phn c
trin khai theo tên  ly tham ching th u
ti các bean khác. Mt bean phiên trng thái có th gi tham chiu ti mt bean thc th. Mt
bean phiên hoc mt thành phn MDB th gi vic tham chiu ti thành phn EJB khác.
Mt bean thc th BMP có th gi mt tham chiu ti bean thc th khác.
5.3.5 Kt hp các kt ni gia các bean thc th
Vmi bean thc th c  bi mt bng quan h. Mi th hin ca c
t hàng trong bng bt k BMP hay CMP. Các quan h gia các bean thc th
C
71
th là mt-mt, mt-nhiu hay nhiu-nhiu, gic quan h d liu trong  d liu
c th hin trong bi quan h-thc th.
d 5.6: Quan h gia bean thc th sinh viên Student bean thc th khóa hc
Course quan h nhiunhiu. Mt sinh viên th  nhiu khóa hc mt khóa
hc th nhiu sinh viên. Th hin các bean thc th y bng CMP trong kin trúc EJB
2.x . Gi s có hai thc th c trin khai ti my và s dng
giao din cc b.
package student;
import java.util.*;
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.naming.Context;
import javax.naming.InitialContext;
public abstract class StudentBean implements EntityBean {
private EntityContext context;
//StudentID and StudentName are CMP fields
public abstract String getStudentID(); //primary key
public abstract void setStudentID(String id);
public abstract String getName();
public abstract void setName(String lastName);
//CMR(container-managed relationship) fields to course bean
public abstract Collection getCourses();
public abstract void setCourses (Collection courses);
//StudentBean next defines its business logic such that
//getCourseList()
//returns all corresponding courses this student has taken and
//addCourse() will add a new course for this student.
public ArrayList getCourseList() {
ArrayList list = new ArrayList();
Iterator c = getCourses().iterator();
while (c.hasNext()) {
list.add(
(LocalCourse)c.next());
}
return list;
}
public void addCourse (LocalCourse course) {
getCourses().add(course);
}
}
//Student Local Home Interface Here’s the LocalStudentHome home
interface for the StudentBean:
import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;
import javax.ejb.FinderException;
public interface LocalStudentHome extends EJBLocalHome {
public LocalStudent create (String studentID, String Name)
C
72
throws CreateException;
public LocalStudent findByPrimaryKey (
String studentID)throws FinderException;
}
}
//The Student bean also defines a local interface. The bean’s
//LocalStudent interface extends the EJBLocalObject interface
//not the EJBObject interface.
import java.util.ArrayList;
import javax.ejb.EJBLocalObject;
public interface LocalStudent extends EJBLocalObject {
public String getStudentID();
public String getName();
public ArrayList getCourseList();
}
c th CMP sinh viên và thc th CMP lp hc có cu trúc rt
ging nhau. Thc th lp hc bao ggetset tt c các sinh
c liên kt ti môn hc c th.
public abstract Collection getStudents();
public abstract void setStudents(Collection students);
Ví d  có th c s dng cho c hai kiu bean CMP và CMR.
Hình 5.5. Quan h kt ni gia các entity bean
Trong Hình 5.5, 3 thc th bean CMP. Bean Dept có quan h mt-nhiu vi bean Student
và bean Studentquan h nhiunhiu vi bean Course. Tt c quan h gia các bean, CMP
BMP, vic thc thi nh bi trin khai các
công c  ng. ràng B i i trin khai phi làm nhiu vic, trong khi
i lp trình cung cp bt c mã SQL nào.
5

 *.war lient trong file .
C
73
  bea file *.class.
gói các  EJB,  Web file nén java
  


  
cho giao  toàn 
v bean 
 
<?xml version=“1.0”>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>studentBean</ejb-name>
<home>studenthome</home>
<remote>student</remote>
<ejb-class>Student</ejb-class>
<persistence-type>Container</persistence-type>
<pri-key-class>Integer</pri-key-class>
...
<cmp-field><field-name>id</field-name></cmp-field>
...
<cmp-field><field-name>name</field-name></cmp-
field>
</enterprise-beans>
<assembly-descriptor>
<security-role>
...
</security-role>
...
</assembly-descriptor>
</ejb-jar>
Hình 5
C
74
5.5 CASE STUDY

        
nhau.
5 hàng
Bean phiên 
 file
sau :
 (CartBean)
Interface  (Cart)
 Interface 
Interface  
 interface nterface 
 interface   javax.ejb.Remote.
package cart.ejb;
import cart.util.BookException;
import java.util.List;
import javax.ejb.Remote;
@Remote
public interface Cart {
public void initialize(String person) throws
BookException;
public void initialize(String person, String id)
throws BookException;
public void addBook(String title);
public void removeBook(String title) throws BookException;
public List<String> getContents();
public void remove();
}

package cart.util;
public class BookException extends Exception {
public BookException() {
}
public BookException(String msg) {
super(msg);
}
}
 
 bean 
 
  interface 
C
75
Bean :
 interface

@PostActivate, @PrePassivate

Package cart.ejb;
import cart.util.BookException;
import cart.util.IdVerifier;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
@Stateful()
public class CartBean implements Cart {
List<String> contents;
String customerId;
String customerName;
public void initialize(String person) throws BookException
{
if (person == null) {
throw new BookException("Null person not
allowed.");
} else {
customerName = person;
}
customerId = "0";
contents = new ArrayList<String>();
}
public void initialize(
String person,
String id) throws BookException {
if (person == null) {
throw new BookException("Null person not
allowed.");
} else {
customerName = person;
}
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
} else {
throw new BookException("Invalid id: " + id);
}
C
76
contents = new ArrayList<String>();
}
public void addBook(String title) {
contents.add(title);
}
public void removeBook(String title) throws BookException
{
boolean result = contents.remove(title);
if (result == false) {
throw new BookException("\"" + title + "\" not in
cart.");
}
}
public List<String> getContents() {
return contents;
}
@Remove()
public void remove() {
contents = null;
}
}
 
package cart.client;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import cart.ejb.Cart;
import cart.util.BookException;
/**
*
* The client class for the CartBean example. Client adds
books to the cart,
* prints the contents of the cart, and then removes a book
which hasn't been
* added yet, causing a BookException.
* @author cnpm
*/
public class CartClient {
@EJB
private static Cart cart;
public CartClient(String[] args) {
}
C
77
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
CartClient client = new CartClient(args);
client.doTest();
}
public void doTest() {
try {
cart.initialize("Duke d'Url", "123");
cart.addBook("Infinite Jest");
cart.addBook("Bel Canto");
cart.addBook("Kafka on the Shore");
List<String> bookList = cart.getContents();
bookList = cart.getContents();
Iterator<String> iterator = bookList.iterator();
while (iterator.hasNext()) {
String title = iterator.next();
System.out.println
("Retrieving book title from cart: " +
title);
}
System.out.println
("Removing \"Gravity's Rainbow\" from
cart.");
cart.removeBook("Gravity's Rainbow");
cart.remove();
System.exit(0);
} catch (BookException ex) {
System.err.println
("Caught a BookException: " +
ex.getMessage());
System.exit(1);
} catch (Exception ex) {
System.err.println("Caught an unexpected
exception!");
ex.printStackTrace();
System.exit(1);
}
}
}
 >cnpm
 > cnpm deploy
cart.
C
78
 t Client
> cnpm run

[echo] running application client container.
[exec] Retrieving book title from cart: Infinite Jest
[exec] Retrieving book title from cart: Bel Canto
[exec] Retrieving book title from cart: Kafka on the Shore
[exec] Removing 

[exec] Result: 1
5etbean
 .
 er-ejb
nterface  Converter
package converter.ejb;
import javax.ejb.Remote;
/**
*
* @author CNPM
*/
@Remote
public interface Converter {
public double cToF(double c);
public double fToC(double f);
}
C
79
 ConverterBean
ConverterBean là bean  Converter
package converter.ejb;
import javax.ejb.Stateless;
@Stateless
public class ConverterBean implements Converter {
@Override
public double cToF(double c) {
return c * 9/5 + 32;
}
@Override
public double fToC(double f) {
return (f - 32) * 5/9;
}
}
Build converter-ejb
-
 converter-ejb: converter-war
Add converter--war
C
80
-war
<%@ page import="converter.ejb.Converter, javax.naming.*"%>
<%@ page import="java.math.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.ejb.*" %>
<%@ page import="java.text.DecimalFormat" %>
<%@ page import="java.rmi.RemoteException" %>
<%!
private Converter converter = null;
public void jspInit() {
try {
InitialContext ic = new InitialContext();
converter = (Converter)
ic.lookup(Converter.class.getName());
} catch (Exception ex) {
System.out.println
("Couldn't create converter bean."+ ex.getMessage());
}
}
public void jspDestroy() {
converter = null;
}
%>
<html>
<head>
<title>Temperature Converter</title>
</head>
<body bgcolor="white">
<h1><b><center> Temperature Converter </center></b></h1>
<hr>
<p>Enter a degree to convert:</p>
<form method="get">
<input type="text" name="degree" size="25">
<br>
<p>
<input type="submit" name="fToC"
value="Fahrenheit to Centigrade">
C
81
<input type="submit" name="cToF"
value="Centigrade to Fahrenheit">
</form>
<%
DecimalFormat twoDigits = new DecimalFormat ("0.00");
String degree = request.getParameter("degree");
if ( degree != null && degree.length() > 0 ) {
double d = Double.parseDouble(degree);
%>
<%
if (request.getParameter("fToC") != null ) {
%>
<p>
<%= degree %> fahrenheit degrees are
<%= twoDigits.format(converter.fToC(d)) %>
centigrade degrees.
<% }
%>
<% if (request.getParameter("cToF") != null ) {
%>
<p>
<%= degree %> centigrade degrees are
<%= twoDigits.format (converter.cToF(d)) %>
fahrenheit degrees .
<% }
%>
<% }
%>
</body>
</html>
 Built project converter-war

-war

C
82
5.6.  
EJB 
 rong môi
  
  bean phiên 
,  bean phiên ph
  EJB
 
bean  thông tin 
bean ar
 bean  
  bean 
  
   SQL 
 

1. 
https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design
2. Trình bày 
3. 
4. 
5. Xây   bán sách onEJB
6.  
EJB
7.  cho thuê xe ôtô 
8. ý 
C
83
9.  
10.  
11. 
TRẦN ĐÌNH QUẾ
GIÁO TRÌNH
KIẾN TRÚC
VÀ THIẾT KẾ PHẦN MỀM
HÀ NỘI - 2017
C
84
THÀNH PHN .NET
Mc tiêu c nhm trình bày:
.NET framework, mt s khái nim chung ca các thành phn .NET.
Các kiu thành phn .NET, kt ni gia các thành phn, và cách trin khai chúng.
Các thành phn cc b và phân tán, các thành phn kt hp và hp thành.
Png b ng b.
Hng dn t xây dng, trin khai, và s dng các thành phn .NET.
6.1 
6.1.1 
.NET là mt trong nhng công ngh ni ting ca Microsoft. Phiên bc
gii thiKhung .NET mt nn tng giúp cho vic xây dng, trin khai,
và chy nhanh chóng các ng dng. Các thành phn ca c tích hp an toàn trong
các ng d phát trin nhanh chóng dch v web các ng dng. .NET
cung cp m, hi da trên thành phn cho các ng
dng hin thi trên Internet. Khung .NET bao gm mt máy  cung cp mt nn tng
mi cho vic phát trin phn mm. Lõi ca .NET bao gm các file XML và giao thc truy
nhn (SOAP:  cung cp dch v web
thông qua Internet.
Ma .NET  thun tin cho vic phát trin các ng dng  bàn
các dch v ng dng da trên nng y làm cho dch v  luôn sn
sàng vàth truy nhc không ch trên nn Windows còn trên các nn tng khác
thông qua các giao thc ph bi (Hình 6.1). t s c
ng ca .NET:
Công ngh  làm n vic thành phn hóa vi công ngh thành phn
COM (Object Model) và công ngh phân tán DCOM. V ngun lý, các thành phn
COM có th s dng ln phn mm kéo th trong vic xây dng
thành phn phn mm ng dng. Tuy nhiên, tin trình phát trit phc
tp và COM không h tr vic thc thi side-by-nguyên nhân y
t gia các phiên bn (v DLL Hell).
Công ngh .NET cho phép trin khai thành phn theo cách lu này cho
phép nhiu phiên bn ca các thành phn cùng tên có th cùng tn ti không
bt k t nào. Công ngh n hóa vic to và trin khai các thành
phn ngoài vic bo mt các dch v tin cycó kh c cung cp
bi các thành phn.
 dàng phát trin các thành phn phân tán bng công ngh truyn
thông t xa. .NET framework h tr kh i hp hong gia các phn
gia COM các thành phn .NET. Mt thành phn th làm vic vi bt k
thành phn ti. Nói cách khác, .NET th cung cp các dch
C
85
v ti các thành phn COM, các thành phn COM th s dng bt k các
thành phn .NET nào. Vic phát trin các thành phn trong .NET d 
trong COM.
Dch v web mt s thay th ca công ngh MS DCOM cho các ng dng
c h tr bi các giao thc XML, SOAP, HTML. .NET gii phóng
vic vit ca các nhà phát trin khi vic l
doanh nghip ln lý giao dch thông qua Enterprise Service. .NET khc
phc vic thiu h tr ng la ca DCOM làm cho các dch v tr nên sn
sàng gia các platform thông qua các giao thc gn kt lng lo XML và SOAP.
.NET framework sn trong SDK Visual Studio .NET IDE SDK, c hai công
ngh u th ti v t MS Website. .NET  ca Visual Studio
.NET và mt phn ct.
.NET framework bao gm 2 phn chính: Common Languague Runtime (CLR)
mt tp thng nht các n ln ca framework bao gm ASP.NET Web
 y dng các ng d xây dng các ng dng
máy nhân truy cp d liu. SDK bao gm tt c các nhu cu
vit, xây dng, kim tra trin khai c ng dng .NET ca bn. h tr tt c
các ngôn ng u ngôn ng khác. .NET
SDK Visual Studio .NET th truy cp các dch v ca tt c các tng trong
nn tng .NET.
6 CLR.
Gig Java, CLR mng máy o nm nh ca h u
hành Windows. CLR bao gm Common Type System (CTS), Just-In-Time IL Compiler
 thc thi), cùng vi các dch v qut ni d
liu qun lý bo mt. Tt c các thành phn phn mm này c tp hp li trong mt
gói assembly (trong kin trúc Java file .jar) bao gm MS Intermediate Language
(MSIL) và file manifest (metadata miêu t v gói này). c biên dch thành mã bn
a bi trình biên dc kim tra li b kim tra tính hp
l ca kiu d liu s d biu din cách hong ca CLR.
C
86
Hình 6.1. .NET framework [21]
.NET framework tích hp nhiu ngôn ng lnt
CLR. Không ch mt thành phn trong mt ngôn ng th truy cp ti các dch v cung
cp bi các thành phn khác trong các ngôn ng lp trình khác mà mt lp trong mt ngôn
ng có th k tha các thuc t các lp có quan h trong các ngôn
ng n lp thng nht (United Class Library) cung cp mt tp các lp th
s dng li cho vic phát trin thành pht tp chun các kiu d liu
các lut cho vic to các kiu mi. CLR cho bit làm th  thc thi các kiu này.
hai loi kiu: kiu tham chiu kiu giá trc thc thi bi
c gi quc ca .NET. Tt c các trình biên dch ngôn ng ca MS
to ra mã  ng vi CTS.
IL ging nha Java, th giao tip vi bt k loi trình
nào thông qua s h tr ca CLR. IL th nh dng tp tin thc thi (.EXE)
hoc n liên kng kiu (.DLL). Nc to ra bi trình biên dch
c gi có qun lý (managed code) ch c thc thi trên nn tng
.NET. Mt s file DLL hoc to ra bi trình biên d
bu cc gi là mã không qun lý c.
Tóm li, CLR là mt máy thc thi hing cao. Nó cung cp mng thc
thi mã trong .NET. Vic qun lý mã bao gm qun lý b nh, lung, bo mt, kim tra mã,
và vic biên dch IL.
C
87
Hình 6.2. CLR ca .NET [21]
6
n lp ca .NET mt tp hp các lp cn th s dng lc t chc
bi không gian tên (namespacen lp này kt ni tt c các lp bao gm Windows
Foundation Classes (WFC) thành mt tp các lp thng nht. Không gian tên ch t
gói trong công ngh n lp giu trúc Java API. Mt không gian tên
bao gm nhiu lp các không gian tên conc trin lp
thành phc t chc thành mt cây phân cp da trên thành phn. Hình 6.3 lit
mt tp các thành phn trong kin tn lp .NET. Tt c các ln
th s dng bi các lp khác có ngôn ng khác nhau.
Namespace gn lp là System, nó bao gm nhiu l
Console, nhiu subnamespace     .Ví d, XML mt
subnamespace ca System vc trin khai thành System.XML.dll, ADO.NET sn
ng vi System.Data, các lp Form-based UI sn trong
  ng vi namespace System.Windows.Forms. Các nhà
phát trin có th tùy chnh namespace và t chc các lp có liên quan trong mt namespace
tùy chnh. Mt namespace có th c trit assembly ca các thành phn nh
phân. Các lp vi tên ging nhau th t trong các namespace khác nhau bi chúng
c tham chiu bi tin t namespacse khác nhau.
C
88
Hình 6n lp .NET [21]
 s dng các lp trong mt namespace, pháp using <namespace> trong C# hoc
pháp import <namespace> trong VB ph phu c vin lp
built-n ca h thc trin khai trong file mscorlib.dll.
6.2. MÔ HÌNH THÀNH PHN CA .NET
Công ngh thành phn .Net ng n hoá s tn ti ca c công ngh MS
COM, DCOM, COM+. Các thành phn MSIL DL thay th các thành phn COM; các thành
phn MSIL Remoting Channels EXE thay th cho thành phn DCOM; Web Service các
thành phn c cho các thành phn dn t.
Các thành phn .NET d dàng phát trii quyt v
t version DLL Hell v firewall trong DCOM. Công ngh thành phn .NET
thành phng ngôn ng hp nht. Bt thành phn nh dng
cc biên dc, nó có th là thành phn nh phân c cm vào bi các
thành phn MISL khác ho
.NET framework t  c xây dng theo hình thành phn. d, System
namespace System.Runtime.Remoting   n trong mscolib.dll System.XML
n trong System.XML.dll. Mt file .dll mt thành phn c trin
khai ca .NET (Assembly). Mt namespace ging mt gói  t chc các class
quan h vi nhau. Mt assembly th nhiu namespace, mt namespace th
m rng trên nhiu file assembly. Chi tit ca .NET assembly s c miêu t trong các
phn sau. Mt thành phn .NET mc biên dc xây
dng t mt hoc nhiu class hoc nhic trin khai trong mt assembly file
DLL. Mt assembly cha bn phn:
Manife assembly, .
Metadata) 
Mã IL 

Mt module MISL siêu d liu ct module
không th tng, nc s dt khi xây dng ti thm biên d xây
dng nên assembly Module file. phn m rng là .netmodule. th mt hoc
C
89
nhiu class trong mt module. Mc to ra t mt hoc nhiu class trong mt
module. Mi module th c code bng nhiu ngôn ng i cùng
phnh dng MSIL. Assembly có m t t thành phn. Mt
assembly mt file .dll hoc .exe kh i sao i ta
gi thành phn .NET mt assembly. Mt file .dll mt file nh phân không kh
c thi, gi.class trong Java.
nhiu kiu thành phn khác nhau trong .NET framework. Chúng ta th phân loi
chúng thành các loi thành phn trc quan hoc không trc quan. Mt thành phn trc
quan mu khin th c trin khai trong mt hp công c (toolbox) d 
m t ca s dng container. Thành phn không trc quan,
c bi   thành phn. Mt .NET thành phn th t phía
client, phía server hoc phía middleware. Kiu ca thành phn không quan trng. Mt
.NET thành phn luôn cung cp mt s dch v cho các client ca chúng (client th
mt thành phn hoc ng dng client khác). Hình 6.4 biu din ni dung ca mt assembly
Hình 6.4. Ni dung assembly ca thành phn.NET [21]
Mt thành phn .NET th mt thành phn cc b (.dll), ch th c truy cp
mt cách cc b (trong cùng min ng dng) trong cùng mt máy hoc mt thành phn
phân tán t xa (.exe) qua nhiu min ng dng. Mt min ng dng mt tin trình
lightweight, th c bu hoc dng li mc lp trong mt tin trình.
ch mt m t lp khác trong .NET. Mt thành phn không th trc tip truy
C
90
cp vào mt thành phn trong min hoc tin trình ng dng khác mi min ng dng
có không gian b nh riêng.
Mt thành phn .NET DLL có th c trit thành phn riêng khi nó bit
c th c trit thành phn c chia s công khai không
bit thành phn DLL có th c kéo th vào Windowns form, Web form
ca DLL hoc ng dng khác. Chúng ta y xem mt thành phn rn trong C#
cung cp các dch v chuyn nhi gia F
0
và C
0
.
using System;
namespace TempConv
{
public class TempConvComp
{
public double cToF(double c)
{
return (int)((c * 9) / 5.0 + 32);
}
public double fToc(double f)
{
return (int)((f - 32) * 5 / 9.0);
}
}
}
Chúng ta có th xây dng mt module t nó vi dòng lnh sau:
>csc /t:module TempConvComp.cs -> TempConvComp.netModule
Module này có th c thêm vào mt thành phn bng cách:
>csc /t:library /addmodule: TempConvComp.netmodule anotherComp.dll
Chúng ta có th xây dng mt DLL thành phn bng dòng lnh
>csc /t:library TempConvComp.cs -> TempConvComp.dll
    a thành phn này. Mt TempConvCSClient.cs trong C# và
TempConvCppClient.cpp trong C++. C 2 s dng li thành phn TempConvComp

using System;
using TempConv;
namespace TempConvCSClient
{
class MainApp
{
public static void Main()
{
TempConv.TempConvComp myCSTempConvComp = new
TempConv.TempConvComp();
double choice;
double input;
C
91
double output;
bool next = true;
while (next)
{
Console.WriteLine("Please enter your choice:");
Console.WriteLine("\t\t 1 - Converter from F to
C");
Console.WriteLine("\t\t 2 - From C to F");
Console.WriteLine("\t\t 3 - exit");
choice = Double.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine("Please tell me the temperature in F:
");
input = Double.Parse(Console.ReadLine());
output = myCSTempConvComp.fToC(input);
Console.WriteLine("result = {0} ", output);
}
else if (choice == 2)
{
Console.WriteLine("Please tell me the temperature in C:
");
input =
Double.Parse(Console.ReadLine());
output = myCSTempConvComp.cToF(input);
Console.WriteLine("result = {0}
",output);
}
else
{
next = false;
Console.WriteLine("see you next time");
}
}
}
}
}
Trong TempConvCSClient.cs, client ti namespace TempConv bng l using
TempConvkhi to mt th hin ca thành phn TempConvComp gi method
fToC() cToF() c thành phn này cung cp. ng dng Client trong C# th c
xây dng bng câu lnh
>csc/t:exe /r:TempConvTemp.dll TempConvCSClient.cs -> TempConvCSClient.exe
 client ca thành phn TempConvComp:
#include "stdafx.h"
#include <iostream>
#using <mscorlib.dll>
#using "TempConv.dll"
C
92
using namespace System;
using namespace std;
#ifdef _UNICODE
int wmain(void)
#else
int main(void)
#endif
{
int choice;
double input;
double output;
bool next = true;
TempConv::TempConvComp *myCSConvComp
= new TempConv::TempConvComp();
while (next) {
Console::WriteLine("Please enter your choice: ");
Console::WriteLine("\t\t1 - Converter from F to
C");
Console::WriteLine("\t\t2 - Converter from C to
F");
cin >> choice;
if (choice == 1) {
Console::WriteLine("Please input the temperature in F : ");
cin >> input;
output = myCSConvComp->fToC(input);
Console::WriteLine(output);
} else if (choice == 2) {
Console::WriteLine("Please input the temperature in C : ");
cin >> input;
output = myCSConvComp->cToF(input);
Console::WriteLine(output);
} else {
next = false;
Console::WriteLine("See you next time");
}
return 0;
}
, trong TempConvCppClient.cpp, client ti namespace TempConv bng #using
 và ly th hin ca thành phn y các dch v thành phn
này cung cp.
Tóm li, client ca mt thành phn to mt tham chin thành phn server ti thi
m biên di thành phn t ng vào min ng dng ca ti thi
gian chy khi cn. nh 6.5 t tin trình ca mt thành phn ti thm biên dch
và thm chy.
C
93
Hình 6.5. Các thành phn .NET ti thm chy và thm biên dch [21]
6
 k .NET
Các t hp thành phn cho phép thành phn tái s dng theo c t hp liên kt t hp
bao hàm. Trong hình t hp liên kt, dch v ca thành phn bên trong s cung cp
dch v trc tip cho thành phn client bên ngoàic innerM( ) ca thành phn
bên trong tr thành mt phn ca giao din vi thành phn .5. d
t chi tic th hi
Hình 6.6. T hp liên kt
Trong t hp bao hàm, nu mt li gn thành phn bên ngoài cn s tr giúp ca thành
phn bên trong, li g c chuyn thành phn Thành phn bên
ngoài giu giao din ca thành phn bên trong. Client không thc vic chuyn giao
li gc outerM( ) y mt li gc innerM( ) ca thành phn
bên  Hình 6.7.
Hình 6.7. Containment
Mt thành phn .NET còn có th c to thành nh vic kt hp t hp liên kt và t hp
bao hàm theo kiu cu trúc phng hoc lng các t hp nhiu m 
mt ví d gii thích vic kt hp các t hp liên kt và bao hàm.
C
94
using System;
namespace NS1
{
public class Inner
{
public void innerM ()
{
Console.WriteLine (“I am Inner.”)
}
}
}
using System;
using NS1;
public class Outer
{
public Inner i = new Inner ();
//aggregation: Outer expose the Inner
public void outerM1 ()
{
Console.WriteLine (“I am outer.”);
}
public void outerM2() //delegation in containment
{
i.innerM();
}
public static void main()
{
outer o1 = new Outer();
Inner i1 = o1.i;
i1.innerM(); //interface to the aggregate
o1.outerM();
o1.outerM2(); // interface to the containment
Inner i2 = new Inner();
i2.innerM();
}
}
Hình 6.8 biu din mt c gi trc tip mt thành phn
Hình 6.8. Li gi trc tip
6 (Event) và  (Delegate)
.NET Delegate mt kic tham chin mt c ging  con
tr hàm trong C++ m bo v kiu. Mt Delegate s y nhim lung
C
95
u khin b u khin s kia khi s kin xy ra. hong
t  t b lng nghe s kin trong Java.
Mt th hin ca Delegate th cha mt ng tha mt lp, hoc mt
c ca mt thành phn, hoc mt c cng là nó. Có hai
kiu Delegate: SingleCast MultiCast. Mt SingleCast ch th y nhim mt 
thc mt long ví d 
Delegate int Mydelegate();
public class MyClass
{
public int ObjMethod() {- - - }
static public int StaticMethod () {- - - }
public class Drive { Static public void Main()
{
Myclass c = new MyClass();
MyDelegate dlg = new MyDelegate(c.objMethod());
dlg();
dlg = new MyDelegate (MyClass.StaticMethod());
dlg();
}
}
Trong d y, MyDelegate mt Delegate tham chin bt c c nào tr
v kiu int và không có tham bia objMethodStaticMethod tha mãn
Delegate MyDelegate. Lnh dlg( ) u tiên gn objMethod lnh dlg( ) th hai gi
c StaticMethod().
MultiCast Delegate kiu tr v void th ni vi nhic, gi
chúng theo th t 
Delegate void MultiDelegate();
MultiDelegate mdlg = null;
mdlg += new MultiDelegate (Method1);
mdlg += new MultiDelegate (Method2);
Vic thc hin bi lnh += Delegate và vic hy b c thc hin
bi lnh -= Delegate.  trò b lng nghe, và b x lý s kin ph
vi b l x lý s kin ngay khi s kic kích hot. Quan h gia s
kin x lý và kích hot s kin thông qua mt c th hin trên Hình 6.9.
C
96
Hình 6.9. Quan h u nhim gia s kin và b x lý ca nó [21]
Mt s kin là mt p c mt ng g gi mt ng
phát ra s kin là ngun s king nhn và x s ki kin. 
mt kiu giao ting s kin gia các thành phn hoc trong cùng mt thành phn.
Lp Delegate mt lp kênh giao tip gia ngun s ki kin. S kin có th
s kit  kin bi Windows Form thành phn.
i phát tri t nh  kin. Th t to s dng s ki
sau:
1. To mt lp delegate.
public class DelegateStart;
2. To mt lp cha min delegate, lp MyClass.
public event DelegateStart EventStart;
- - -
3.  x lý s kin.
public void handleEvent(){ - - -}
4. Kt ni s kin y nhim vi mt b x lý s kin thông qua b lng nghe s kin,
kích hot mt s kin, gn b x lý s kin.
Public static void Main() { MyClass EventObj = new
MyClass();
EventObj.EventStart += new DelegateStart(handleEvent);
EventObj.EventStart();
...
}
6
Mt thành phn hay mt client không th truy nhp trc tip ti mt thành phn t 
chy trên mt min ng dn trình khác tr phi s dng kênh
kt ni t xa. hai cách to  th gi mc t xa ca mt
thành phn phân tán: Theo kiu MBV (Marshal by Value), server truyn bn sao ci
C
97
ng cho client; theo kiu MBR (Marshal by Reference), client s to mt tham chiu ca
ng t xa. MBR là la chn duy nht khi thành phn t xa chy trên mt phía xa.
Các client giao tip vi các thành phn t xa thông qua các giao thc. Ví d s
dng kênh TCP (TCP channel). T n thông kiu socket trong Java, mi
giao thnh bi mt cng ng. Chúng ta to kênh TCP trên cng 4000
i lp t xa và tên URI mà client s s d lng ca thành
phn t i to m phía client.
 ca mt thành phn phân tán client ca nó. Chúng chy ch 
t xa (tc chy trên c min ng dng hay các tin trình khác bit) vn s dng thành
ph c xây dng t thành phn c
truy nhp t xa.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
public class CoTempConv : MarshalByRefObject
{
public static void Main()
{
TcpChannel channel = new TcpChannel(4000);
ChannelServices.RegisterChannel(channel);
RemotingConfiguration.
RegisterWellKnownServiceType (
typeof(CoTempConv),
"TempConvCompDotNet",
WellKnownObjectMode.Singleton);
System.Console.WriteLine("Hit <enter> to
exit...");
System.Console.ReadLine();
}
public double cToF(double c)
{
return (int)((c*9/5.0+32)*100)/100.0;
}
public double fToC(double f)
{
return (int)((f-32)*5/9.0*100)/100.0;
}
}
a thành phn trên.
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
class MainApp
{
public static void Main()
C
98
{
try
{
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel);
CoTempConv myCSTempConvComp =
(CoTempConv)Activator.GetObject(
typeof(CoTempConv),
"tcp://127.0.0.1:4000/
TempConvCompDotNet");
double choice;
double input;
double output;
bool next = true;
while (next)
{
Console.WriteLine("Please enter your
choice:
1 - Converter from F to C,
2 - from C to F,
3 - exit");
choice=Double.Parse (Console.ReadLine());
if (choice == 1)
{
Console.WriteLine("Input temperature in F: ");
input=Double.Parse(Console.ReadLine());
output =
myCSTempConvComp.fToC(input);
Console.WriteLine(output);
}
else if (choice ==2)
{
Console.WriteLine("Input temperature in C:");
input=Double.Parse(Console.ReadLine());
output = myCSTempConvComp.cToF(input);
Console.WriteLine(output);
}
else
{
next= false;
Console.WriteLine ("See you next time.");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
C
99
Hình 6.10: Li gng b t xa ca thành phn phân tán
c xây dng server và client
>csc TempConvComp.cs
>csc /r:TempConvComp.exe TempConvCSClient.cs
 kích hot thành phn server phân tán và client ca nó, chúng ta chy dòng lnh sau:
>TempconvComp.exe
>TempConvCSClient.exe
Client tham chiu ti thành phn t xa bng Activator.GetObject() gc
ca thành phn t xa này. Hình 6.10 ch ra li gng b t xa ca mt
thành phn phân tán.
6 
Gi ng b t xa da trên Remoting Delegate. Nó s không khóa client trong
khi ch thông báo t các thành phn t xa. d, gi s mc thông báo
ngay khi giá c phit ti m . Thay thông báo giá c phiu ti mi thi
m, t cho server thc hin tng hp cho bn còn bn có th làm bt c cái
bn mun. Trong mt s ng hp khác, các công vic thc hin trên server mt khá
nhiu thi gian, t cho server thông báo cho bn khi công vic
hoàn thành.
Chúng ta s dng li thành phn TempConvComp c trình bày o các
li gi ng b t server ti client. Git chu trình, khi client thc hin li
gng b tc ca thành phn t xa, truyn mc gi li ti
    c gi li thông qua Remoting Delegate. hai Delegate: Mt
Mydelegate tr t  c t xa cToF ca thành phn t xa tên
TempConvDotNET   ng b khác AsynchCallback c truyn vào
c BeginInvoke ca Mydelegate
using System;
using System.Threading;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
public class Client {
public delegate double MyDelegate(double c)
public static int main(string [] agrs)
C
100
TcpChannel chan = new TcpChannel();
ChannelServices.RegisterChannel(chan);
CoTempConv obj =
(CoTempConv)Activator.GetObject(typeof(CoTempConv),
"tcp://localhost:4000/TempConvCompDotNet");
if(obj == null)
System.Console.WriteLine("Could not locate
server");
else {
AsyncCallback cb =
new AsyncCallback(Client.MyCallBack);
MyDelegate d = new MyDelegate(obj.cToF);
IAsyncResult ar = d.BeginInvoke(32, cb, null);
}
System.Console.WriteLine(“Hit <enter> to exit ...
”);
System.console.ReadLine();
return 0;
}
public static void MyCallBack(IAsyncResult ar)
{
MyDelegate d =
(MyDelegate)((AsyncResult)ar).AsyncDelegate;
Coinsole.WriteLine(d.EndInvoke(ar));
Coinsole.WriteLine("See you next time");
}
}
Hình 6.11: Gi li c kng b ca thành phn phân tán
 nhn thy hai Delegate. Mt MyDelegate tr tc t
a thành phn phân tán, hai AsynchCallback tr tc quay lui
.11 minh ha li gng b ca thành phn
c trình bày trên.
Tham s u tiên ca BeginInvoke  C tham s th hai mt Delegate gi
li. Gi li s n phân tán hoàn thành công
vic chuyc gi li s c gi và IAsyncResult c tr li cho client.
6.4 MÔ HÌNH TRIN KHAI THÀNH PHN .NET
Thành phn .NET có th t thành phn riêng hoc thành phn chia s
chung trong mt file assembly. Assembly m   trin khai  n trong .NET.
C
101
Thành phn riêng thành ph c plug-in. Thành phn chia s chung
không bit thành phn nào s s dng ph
Cache (GAC). Thành phn chia s h tr nhiu phiên bn thc thi thành phn cnh nhau.
6
Thành phc trin khai trên mc các client hoc thc con các client.
n nhc thc hin bng cách copy tt c c thành phn ti
 b vic tric thc hin bng cách xóa b mi thành
phn c. Thành phn riêng không h tr kim soát vinh phiên bn
ch trin khai trong ni b ca mt công ty. Hình 6.12 minh ha d v trin khai
riêng.
>csc /t:library /out:dir1\comp1.dll comp1.cs
>csc /t:library /out:dir2\comp2.dll comp2.cs
>csc /r:dir1\comp1.dll, dir2\comp2.dll /out:client.exe client.cs
Cn có mt file miêu t cu hình XML nu các thành pht trong cùng
c vi client cng dn riêng phnh trong th con probing ca
th assembly building trong file cu hình ng dng vi phn m r
Hình 6.12: Cc trin khai thành phn riêng [21]
 ca file cu hình:
<configuration>
<runtime>
<assemblyBinding>
<probing privatePath = “dir1; dir2”/>
</assemblyBinding>
</runtime>
</configuration>
CLR s s dng d tìm kim thành phn cn thi ti nu nó không tìm
thy thành phn cn thic hin thi.
6
Cách trin khai thành phn kh i ph bin nht là trin khai thành phn vi
mt tên  i GAC. Thành phn chia s strong name th duy nht
nh bi cp khóa public/private. Thành phn chia s i GAC có th
c chia s m c c to ra mt thành phn .NET chia s là:
c 1: To mt cp khóa public/private bng cách s dng sn.exe
C
102
>sn k mykey.snk
 xác minh lc th hin t ch
s thành phn a
assembly. Khi client tham chin thành phn, thông báo c
trong assembly ca client.
c 2: Nhúng các dòng sau vào mã ngun ca thành phn
using System.Reflection:
[assembly:AssemblyKeyFile (“mykey.snk”)]
[assembly:AssemblyDelaySign (false)]
[assembly:AssemblyVersion (“1,2,3,4”)]
Lnh sau s gán ch ký vào thành phn ngay lp tc
>csc /t:library mythành phn.cs
Lnh tip theo s a khóa public vào thành phn ca client
>csc /r:mythành phn.dll /out:myapplication.exe myapplication.cs
Nu cn trì hoãn vic gán ch ký, chúng ta có th gán ch ký sau bng cách dùng lnh:
>sn R mythành phn.dll mykey.sn
Ch c xác minh khi thành phn  m bo
rng thành phn không b thay c xây dng. Trong khi chy, mã
thông báo ca khóa public trong manifest cc xác minh vi khóa public
mt phn c nh danh thành phn. N   ng v     
chính là thành phn mong mun.
Hình 6.13 ch ra cp khóa public và private trong manifest ca thành phn và ca thành
phn phía client. S phiên bn ca thành phn chia s u bi bn s khác nhau
cách nhau bi du chnh dng major.minor.build.revision. Vic thc
t bnh phiên bn ca .NET. .NET framework cho phép các thành phn
phiên bn khác nhau cùng tên chy trên các ng dng khác nhau. CLR kim tra các
s c tiên. Theo mnh, ch cho phép phn major.minor hp l. S
build theo mnh s c. i các khác, phiên b
vi 1.2.4.0. Nu s phiên bn trong manifest
ca thành phn i thành phn nào trong GAC, s np mt thành
phn phiên bn khác nhau v s revision. S  c gi Quick Fix
Engineering (QFE) mn mch
có th c tùy bin bc t assembly trong file cu hình. Ví d:
<assemblyIdentity>
<binding Redirect oldVersion = “1.2.3.4” newVersion =
“2.0.0.0”/>
</assemblyIdentity>
C
103
n có phiên bn 2.0.0.0 s c np thay vì thành phn 1.2.3.4.
c 3: n chia s vi GAC
>gacutil /I mythành phn.dll
c 4: S dng thành phn chia s
Client phi to tham chin thành phn chia s  c s dng
>csc /t:exe /r:mythành phn.dll /out:myapp.exe myapp.cs
Hình 6.13: cp khóa public/private trong thành phn .NET
 s dng li thành phn chia s, ngun client phi s dng không gian tên sn
trong assembly. Mt ví d v trin khai thành phn chia s 
using System;
using System.Reflection;
[assembly:AssemblyVersion("1.0.0.0")]
[assembly:AssemblyKeyFile("originator.key")]
namespace TempConv
{
public class TempConvComp
{
public TempConvComp()
{
}
public double cToF(double c)
{
// how to control output format
return (int)((c*9/5.0+32)*100)/100.0;
}
public double fToC(double f)
{
// how to control output format
return (int)((f-32)*5/9.0*100)/100.0;
}
}
}
c sau ch ra cách xây dng thành phn chia s:
>sn -k originator.key
>csc /t:library /out:TempConv.dll TempConvComp.cs
>gacutil /i TempConv.dll
C
104
>csc /r:TempConv.dll /t:exe /out:TempConvCSClient.exe
TempConvCSClient.cs
Mã ngun c  trong phn 6.2.
6.5 
Cthành hành ph
file -. 

. 



1.  trong .NET
Passing and Marshalling http://blogs.msdn.com/b/tq/archive/2005/10/06/478059.aspx
2. 
3. So sánh mô 
4.   
5.  
6. 
.NET
7. 
8. 
9. 
10. 
11. 
12. 
.NET
CH: 
105
C: 

 

s
7 
(design pattern)  
     . K
 ngành kher Alexander
  
.
Kent Beck
War Cunninghatrình y áp ý 
 dành  
quan tâm . 
sách ign Patterns: Elements of Reusable Object-
(GoF) Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides  
  các . 
  :
Mu thit k là mt cách hiu qu  truyn ti nhng nhng thit kchng.
th t vng ca mt phn t thit k  gii quyt v p phi
hay là mt ngôn ng  i kinh nghim.
Mu thit k không phi mt mt phn tài liu bàn v
cách gii quyt mt v c xem hu hiu nht qua kinh nghim xây dng
nhiu h thng phn mm.
Không phi cái tt nht trong thc t c xem mu phi tha mãn
Quy lut t này cho rng mẫu đó phải được chng t lặp đi lặp
li tt nht trong ít nht ba h thng đã xây dựng. a lut này
nhm m bo rng mt s chuyên gia phn mm ng dng gi xut
 gii quyt mt s v trong thit k phn mm ri.
Mc các mu thit k ng c xem xét trong bi cnh phát trin phn mm ng
 chúng th c áp dng trong nhiu c khác vi các cách tip
cn lp trình khác nhau. Ch vi mt s i nh, mt mu thit k th u
ch to ra mu thit k mi.
Các mu thit k không cung cp các gii pháp cho mi v trong thit k phát
trin phn mm thc t ch  các gii pháp tái s d gii quyt các v
phát trin phn mng gp trong mt bi cnh c th ng
ch các hình cung cp các gii pháp tt nht cho mt v trong mt ng cnh
CH: 
106
c th  không th hiu qu trong ng cnh khác. vy, các gii pháp ca
các mu thit k  xut th áp dng trong ng ckhông áp dng
c trong mt s ng cnh khác.
Mu thit k và Framework
Mu thit k không tn ti dng thành phn phn mm pht ti
thm s dng, không nên nhm ln gia framework vi mu thit k. Framework là
mt dng phn mm gm các thành phn phi hp hong v cung cp mt
kin trúc cho mt min ng dng nên th t nhiu mu thit k. Bng 7.1 sau
 mt s m th hin s khác bit này [10]:
-1
Mu thit k
Framework
Mu thit k gii pháp lp li
vi v ny sinh trong i ca ng
dng phn mm
Framework nhóm thành phn cng hp
v cung cp mt kin trúc th
s dng li cho nhng ng dng
M
Giúp ci tin ch ng phn mm
(s dng li, bo trì, m r
Gim thi gian phát trin
M
Giúp ci tin ch ng phn mm
(s dng li, bo trì, m r
Gim thi gian phát trin
Mu là mt cu trúc logic
Framework là mt dng phn mm
Mô t mc lp vi ngôn ng lp
trình và chi tit
t
Mu t      s dng
trong nhiu ng dng
Framework cung cp ch   n
c th
Mu thit k không tn ti dng thành
phn phn mm. c   t mi
khi s dng
Framework không phi là mt ng dy
, các ng dng có th xây dng bng cách
k tha t các thành phn có sn
Mu thit k cách thit k tc s
d thit k các framework
Mãu thit k th s dng trong thit k
      
framework có th cha nhiu mu thit k
7
các  
. 
. 
  
là m  :
CH: 
107
Tên mu: Tên vit ngn gn ca mu ng mt hoc hai t. d, tên mu
phi chn làm sao th hic ma c s dt
tên duy nh
Phân loi: Các mc phân chia thành nhiu loi khác nhau. Nhóm mu to
dng (creational) các mu tp trung vào cách to ng; nhóm mu cu
trúc (structural) tp trung vào vic sp xng vi nhau thành mt cu
trúc tng th l nhóm mu hành vi n hành vi, cng
tác gi thc hin mt m.
Mục đích: Mt t chung ngn gn (mt hoc hai câu) v hình. d, mu
Observer t ph thuc 1-nhiu gi khi mng thay
i trng thái thì tt c ph thuc ca nó có th nhn bit và cp nht t ng.
Định danh: Các mu nh danh ca m
Động lc: nh v mà mu thit k này có th c s dng  gii quyt.
Kh năng áp dụng: c mà mu thit k này có th c s dng.
Cu trúc: Nhng bi lp thành phn vi UML nhm th hin cách hot
ng mu thit k này.
Các bên tham gia: nh ng liên quan hoc nhng công vii
c yêu cu thc hin.
Cng tác: nh s cng tác ca các bên tham gia.
Kết qu: Li ích hn ch ca mu thit k này (thêm nhng g gii quyt
các v v hn ch).
Cài đặt: Nhng gi ý, ch dn v cách s dng mu này bao gm c nhng th
thut, các cách ng dng hiu qu và nhu nên tránh.
ngun mu: d tri cho mc vii dng ngôn
ng C++, java, C#
Các áp dng: Ví d v c mà mu này c áp dng trong thc t.
Các mu liên quan: Các mu thit k  u này hoi
hiu qu  khi s du hin thi.
 
  nhóm thêm
[10].     nhóm GoF.
  
   23
  , nhóm 
hành vi.
Nhóm  
  các

    
.
CH: 
108


interface 
   các     : Abstract Factory, Factory Method,
Builder, Prototype, và Singleton.
Nhóm 






 
 , 


Nhóm này g  : Adapter, Bridge, Composite, Decorator, Façade,
ProxyFlyweight.
Nhóm hành vi
Nhóm 

u
kh
  
 
: Interpreter, Template Method, Chain of
Responsibility, Command, Iterator, Mediator, Memento, Observer, State, Strategy
Visitor.

ác  sinh
viên 
. N 
 https://www.tutorialspoint.com/design_pattern/index.htm.
CH: 
109
7
7.4.1 Khi nào ?
  
tro 
trong các 
Mẫu thiết kế được hiểu theo nghĩa tái sử dụng ý tưởng hơn là tái sử dụng mã lệnh. 
 
         
          
m.  
 trong quá trình 
  
  sau này .
Mẫu thiết kế hỗ trợ tái sử dụng kiến trúc hình thiết kế phần mềm quy
lớn.     

  

 
Mẫu thiết kế đa tương thích  
n hay Microsoft .NET. 
    
       
               
Factory, Proxy, Adapter...
7.4.2 S  nào?
  S
    :
S khác bit v ngôn ng biên dch: Các ngôn ng lp trình k c các ngôn ng
u nhng khác bit nhau ch...ác
mu thit k cn phi hiu chnh sao cho phù hp vi ngôn ng  dng cho
d án.
S khác bit v quan điểm: ng, th nhiu gii pháp i vi mi
v  t ra trong khi thit k   mt mu thit k c   bi mt
chuyên gia hoc mt nhóm các chuyên gia hoàn ho.
S khác bit v kiu: Thit k kiu hóa th ny sinh t nhiu ngu
kinh nghim, nguyên tc vit ca doanh nghip, các yêu cu ca mn
hoc framework. Nu mt hình không phù hp vi kiu d án s dng thì
chúng ta phi u chnh nó.
CH: 
110
Vấn đề khác nhau: Mi mt mu thit k phi c th hin ht sc tng quát nên
mt s mô hình lp trình bày trong mu có th s c s dng. Ví d, trong
mu thit k Observer   , các lp ConcreteObserver
ConcreteSubject th c s dng không phù hp vi tình hung thit
k ca chúng ta.
Thành phn, kế thừa và đa kế tha: Các ngôn ng ng và các nhà phát
trin ng có s khác bit trong cách s dng k tha và thành phn. Ví d, trong
 thi không có.
Đơn giản hóa: Mt mu thit k ng là tng quát hóa cho nhiu do
th s phc tthc t thit k ca yêu cu d án  ra. Vì vy, chúng ta
có th làm n mm mang li hiu qu 
7.5 
    
 

Chi    
trong các 
CH: 
111

1.  interface 

     
     CategoryA, CategoryB…    getSalary () 
interface SalaryCaculatorEmployee SalaryCaculator 
display().
a.  
b. L


Nhân viên



15
ý 







2. interface Search ách Book trong
BinarySearch 
LinearSearch 
3. interface AddressValidator   
khác               

4. , 
Employee sSalesRep, nhân
Consultant Employee:


Tính 
a.  


b. 
CH: 
112
: CÁC 
  dun

factory method

Abstract factory
Prototype
Builder
8.1  FACTORY METHOD

Tr

 ,

Tuy nhiên,  
 con nào. 
 

Gây nên 
K




   
factoryMethod

 
khác
  
 Hình 8.1, trong Hình 8.2, factoryMethod 

factoryMethod 
abstract interface Creator factoryMethod()
ConcreateCreator  factoryMethod()
CH: 
113
factoryMethod() trong
                 
factoryMethod().
Hình 8.1
Hình 8.2ethod

actory method:
Khi         ng    
factory method  cho phép khi 
.
 
.
Khi ta 
.
CH: 
114
Khi ta 
Factory
Method tên khác nhau.
Factory Method  Abstract Factory Prototype 
.  Factory Method Template
Method.

 ng. 
 

interface Logger 

     FileLogger          
ConsoleLogger  Hãy xét xem 
LoggerTest Ta
          logger.properties     
Logger 
Logger (Hình 8.3).
Hình 8.3: 
Logger 
      getLogger   LoggerFactory (Hình 8.4).
LoggerFactory getLogger ConcreteCreator 
Hình 8.2.
CH: 
115
Hình 8.4

//Logger
public interface Logger {
public void log(String msg);
}
//FileLogger
public class FileLogger implements Logger {
public void log(String msg) {
FileUtil futil = new FileUtil();
futil.writeToFile("log.txt”, msg, true, true);
}
}
//ConsoleLogger
public class ConsoleLogger implements Logger {
public void log(String msg) {
System.out.println(msg);
}
}
//LoggerFactory
public class LoggerFactory {
public boolean isFileLoggingEnabled() {
Properties p = new Properties();
try {
p.load(ClassLoader.getSystemResourceAsStream(
"Logger.properties"));
String fileLoggingValue =
p.getProperty("FileLogging");
if (fileLoggingValue.equalsIgnoreCase("ON") == true)
return true;
else
return false;
} catch (IOException e) {
return false;
}
CH: 
116
}
//Factory Method
public Logger getLogger() {
if (isFileLoggingEnabled()) {
return new FileLogger();
} else {
return new ConsoleLogger();
}
}
}
//LoggerTest
public class LoggerTest {
public static void main(String[] args) {
LoggerFactory factory = new LoggerFactory();
Logger logger = factory.getLogger();
logger.log("A Message to Log");
}
}
8.2  SINGLETON
8.2
H  
thêm, xóaràng,  
 này. Singleton 
. Singleton 

8.
Singleton getInstance()
static Singleton.

singleton abstract factory, builder, prototype.

FileLogger 
interface Logger log.txt. 


FileLogger 

CH: 
117
Hình 8.5
FileLogger 
  

 
FileLogger. Hai            
log.
giám sát 
               
log(String) 
FileLogger.
log
FileLogger 
FileLogger 
Hình 8.6).
Hình 8.6
//Singleton Filelogger class
public class Filelogger implements Logger{
private static FileLogger logger;
//Ngăn ngừa client sử dụng cấu tử
CH: 
118
private FileLogger(){
}
public static Filellogger getFileLogger(){
if (logger == null){
logger = new FileLogger();
}
return logger;
}
public synchronized void log(String msg){
FileUtile futil = new FileUtil();
Futil.writeToFile(“log.txt”, msg, true, true);
}
}
//Lớp LoggerFactory
public class LoggerFactory {
public boolean isFileLoggingEnabled() {
Properties p = new Properties();
try {
p.load(ClassLoader.getSystemResourceAsStream(
"Logger.properties"));
String fileLoggingValue =
p.getProperty("FileLogging");
if (fileLoggingValue.equalsIgnoreCase("ON") == true)
return true;
else
return false;
} catch (IOException e) {
return false;
}
}
//Factory Method
public Logger getLogger() {
if (isFileLoggingEnabled()) {
return new FileLogger();
CH: 
119
} else {
return new ConsoleLogger();
}
}
}
private cho cprivate FileLogger() 
FileLogger c khác trong FileLogger 

8.3  ABSTRACT FACTORY
8.3
T giao 
                trong
ch      owerpoint, c         

...


  
Resize(), SetPosition()
chung c  

 nh
Powerpoint,
WidgetFactory 
 
AbstractFactory   cung c
interrface   

8.3
rong Hình 8.7. 
AbstractFactory:  
AbstractProductAAbstractProductB.
ConcreteFactoryX:      AbstractFatory       

CH: 
120
AbstractProduct: 

Hình 8.7
8.3
 
.
Phía trình khách 
nào.

.
            

8.3
Chúng ta ShapeColor  c 
này https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm).  
      AbstractFactory.  
Factory ShapeFactory ColorFactory  AbstractFactory. 
   FactoryProducer (Hình 8.8)  AbstractFactoryPatternDemo 
 FactoryProducer AbstractFactory. CIRCLE
/ RECTANGLE / SQUARE cho Shape  AbstractFactory      
 RED / GREEN / BLUE cho Color  AbstractFactory 
.
CH: 
121
 

public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
CH: 
122
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("Inside Green::fill() method.");
}
}
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Inside Blue::fill() method.");
}
}
public abstract class AbstractFactory {
abstract Color getColor(String color);
abstract Shape getShape(String shape) ;
}
public class ShapeFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
CH: 
123
return null;
}
@Override
Color getColor(String color) {
return null;
}
}
public class ColorFactory extends AbstractFactory {
@Override
public Shape getShape(String shapeType){
return null;
}
@Override
Color getColor(String color) {
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
}else if(color.equalsIgnoreCase("GREEN")){
return new Green();
}else if(color.equalsIgnoreCase("BLUE")){
return new Blue();
}
return null;
}
}
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
CH: 
124
}else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
//get shape factory
AbstractFactory shapeFactory =
FactoryProducer.getFactory("SHAPE");
//get an object of Shape Circle
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Shape Circle
shape1.draw();
//get an object of Shape Rectangle
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Shape Rectangle
shape2.draw();
//get an object of Shape Square
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of Shape Square
shape3.draw();
//get color factory
AbstractFactory colorFactory =
FactoryProducer.getFactory("COLOR");
//get an object of Color Red
Color color1 = colorFactory.getColor("RED");
//call fill method of Red
color1.fill();
//get an object of Color Green
Color color2 = colorFactory.getColor("Green");
//call fill method of Green
color2.fill();
CH: 
125
//get an object of Color Blue
Color color3 = colorFactory.getColor("BLUE");
//call fill method of Color Blue
color3.fill();
}
}
8.4  BUILDER
8.4
 

  


hay  
 và phân 
 

           

 

 người xây
dựng (builder)
  
thành     các
 
8.4

AddressDirector Address
AddressBuilder  Address 
Address.
USAddressBuilder   Address. USAddressBuilder     

CH: 
126
Hình 8.8
8.4
 quan
 
 . 

8.4
 Address    

Address.java
Address.java
class Address{
private String street;
private String city;
private String region;
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return the region
*/
public String getRegion() {
return region;
}
/**
* @param region the region to set
CH: 
127
*/
public void setRegion(String region) {
this.region = region;
}
/**
* @return the street
*/
public String getStreet() {
return street;
}
/**
* @param street the street to set
*/
public void setStreet(String street) {
this.street = street;
}
}
AddressBuilder.java
abstract class AddressBuilder{
abstract public void buildStreet(String street){}
abstract public void buildCity(String city){}
abstract public void buildRegion(String region){}
}
USAddressBuilder.java
class USAddressBuilder extends AddressBuilder {
private Address add;
public void buildStreet(String street){
add.setStreet(street);
}
public void buildCity(String city){
add.setCity(city);
}
public void buildRegion(String region){
add.setRegion(region);
}
public Address getAddress(){
return add;
}
}
AddressDirector.java
class AddressDirector{
public void Contruct(AddressBuilder builder, String street,
CH: 
128
String city, String region){
builder.buildStreet(street);
builder.buildCity(city);
builder.buildRegion(region);
}
}
Client.java
class Client{
AddressDirector director = new AddressDirector();
USAddressBuilder b = new USAddressBuilder();
director.Contruct(b. “Street 01”, “City 01”, “Region 01”);
Address add = b.getAddress();
}
8.5  PROTOTYPE
8.5
o
 Prototype  
 
 

8.5.2 
 
Hình 8.10

Prototype         myClone()   

ConcretePrototype1ConcretePrototype2 Prototype.
8.5
Khi . 

CH: 
129
8.5.4 

Hình 8.11 prototype

           
 
 


1. .
2. LoggerFactory getLogger 

3. 
4. tract factory 
:


 


5. 
6. 
7. .4

130

 
 :
dapter

omposite
ecorator
açade
lyweight
roxy
9.1 ADAPTER
9.1.1 
Xét  :
M  dùng 
không thích   o
 Adapter 
T, tuy nhiên 
   
 
 c. 




 
  .
9.1.2 
C
Target Interface  
Adaptee  Target 
Target .
Adapter  Target Adaptee, Apdater
Adaptee vào Target 
.

131
Hình 9.1: Adapter
9.1.3  
      
.
  
  .
9.1.4 
           
 ý 
  các ký   và t
  
//Giao tiếp PhoneTarget
public interface PhoneTarget{
public String getPhoneNumber(String message);
//lấy số điện thoại trong một xâu
}
public GetNumberAdaptee{
public String getNumber(String str){
//lấy ra dạng số trong một xâu
<…get number>
}
}
public Adapter implements PhoneTarget{
public String getPhoneNumber(String message){
GetNumberAdaptee obj = new GetNumberAdaptee;
String str = obj.getNumber(message);
return “84”+str;
}
}
9.2 
9.2.1 
Khi   t
 
 không

132
ràng   
 
  
  .
9.2.2 

Hình 9.2

Abstraction: 
  interface Implementation
abstractionOp() .
Interface Implementation: 
Abstraction.
RefineAbstractionX:       
trong Abstraction.
ConcreteImplementY: 

9.2.3 
  

 Các abstraction các th



 
a

các client.



133

chúng
 
 
 trong khi 
  


9.2.4 
Interface DrawAPI       Bridge      RedCircle,
GreenCircle 
DrawAPI. BridgePatternDemo Shape 
nhau [23].
Hình 9
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
}
public class RedCircle implements DrawAPI {
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: red, radius: " +
radius + ", x: " + x + ", " + y + "]");
}
}
public class GreenCircle implements DrawAPI {

134
@Override
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: "
+ radius + ", x: " + x + ", " + y + "]");
}
}
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
this.radius = radius;
}
public void draw() {
drawAPI.drawCircle(radius,x,y);
}
}
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new
GreenCircle());
redCircle.draw();
greenCircle.draw();

135
}
}
9.3  COMPOSITE
9.3

cho  
   các
ra
các thành p 


 

 
  xem xét
 
            bi   
 các thao tác truy
 
 
              


Hình 9.4


136
Component interface 
g khi ta 
Component không
 
.
CompositeComposite 
óm các Component
    Component       
Component Composite 
           Composite    
.
Leaf        Component      Leaf
Composite Leaf Component 
Leaf  
 
--hay khi
.
 y 
Chain of Responsibility
 Khi Decorator 
       
            
Flyweight giúp 

 Các

9.3.4 
  ProjectProject Task (Leaf), ta
 . 

public interface TaskItem{
public double getTime();
}
public class Project implements TaskItem{
private String name;
private ArrayList subtask = new ArrayList();
public Project(){ }
public Project(String newName){
name = newName;
}

137
public String getName(){ return name; }
public ArrayList getSubtasks(){ return subtask; }
public double getTime(){
double totalTime = 0;
Iterator items = subtask.iterator();
while(items.hasNext()){
TaskItem item = (TaskItem)items.next();
totalTime += item.getTime();
}
return totalTime;
}
public void setName(String newName){ name = newName; }
public void addTaskItem(TaskItem element){
if (!subtask.contains(element)){
subtask.add(element);
}
}
public void removeTaskItem(TaskItem element){
subtask.remove(element);
}
}
public class Task implements TaskItem{
private String name;
private double time;
public Task(){ }
public Task(String newName, double newTimeRequired){
name = newName;
time = newTimeRequired;
}
public String getName(){ return name; }
public double getTime(){
return time;
}
public void setName(String newName){ name = newName; }
public void setTime(double newTimeRequired){ time =
newTimeRequired; }
}
9.4 

 
 

138
   
(gán 

. 
Component: 
ConcreteComponent: 

Decorator:   
          

ConcreteDecoratorX:           


Hình 9.5or
9.4.3 T 
Khi chúng ta   không
; 
  
 

mà không  Adapter 
             

Decorator  vào cho phép chúng ta thay
          strategy    

139
cho p
 thay 
9.4.4 

LibraryItem , ngoài các
  thông tin   

  D 
t).
 interface LibraryItem display() 
 Book Video 
LibDecorator.
Hình 9.6: Decorator ý 

//Định nghĩa giao tiếp
public interface LibraryItem{
public void display(); //đây là defaultMethod
}
//Định nghĩa các lớp tài liệu
public class Book implements LibraryItem{
private String title;
private int page;
public Book(String s, int p){
title = s;
page = p;
}
public void display(){
System.out.println("Title: " + title);
System.out.println("Page number: " + page);
}
}
public class Video implements LibraryItem{
private String title;

140
private int minutes;
public Video(String s, int m){
title = s;
minutes = m;
}
public void display(){
System.out.println("Title: " + title);
System.out.println("Time: " + minutes);
}
}
//Lớp trừu tượng Decorator thư viện
public abstract class LibDecorator implements LibraryItem{
private LibraryItem libraryitem;
public LibDecorator(LibraryItem li){
libraryitem = li;
}
public void display(){
libraryitem.display();
}
}
//Các lớp Decorator cho mỗi tài liệu thư viện cần bổ sung
//trách nhiệm ở thời điểm chạy
public class BookDecorator extends LibDecorator{
private String borrower;
public BookDecorator(LibraryItem li, String b){
super(li);
borrower = b;
}
public void display(){
super.display();
System.out.println("Borrower: " + borrower);
}
}
public class VideoDecorator extends LibDecorator{
public VideoDecorator(LibraryItem li){
super(li);
}
public void display(){
super.display();
play(); //phương thức play video
}
}

141
9.5 FAÇADE
9.5.1 
 
   
 AccountAddress CreditCard 

T    hóa
u y
client 
. 
các vai trò  . 
façade 
con  làm cho các  
 có và không có façade (Hình 9.7 và 9.8).
Hình 9.7
Hình 9.8

142


Hình 9.9: Façade
Hình 9.10 Façade


Façade 
 1 và Class2.
áp 
Façade l 
.
Façade  
 
d

143
TMediator   hóa  
Façade  
                
Tuy nhiên, Mediator  hóa 

9.5.4 
 Circle, Square, Rectangle (Hình
9.11)    interface Shape        Shape  
ShapeMaker   
FacadePatternDemo ShapeMaker này [23].

public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
public class Circle implements Shape {
@Override
public void draw() {

144
System.out.println("Circle::draw()");
}
}
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;
public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}

145

9.6.1 
 
   cài 
.  
 .
Khi   
 Nên s 
:

  


phân rã. V

9.6.2 
Hình 9.12: Flyweight

FlyweightFactoryFlyweight
Flyweight:  interface 
ConcreteFlyweightXFlyweight
 bên ngoài.

146
9.6.3 T 
. 

.

.

chúng.
và t

9.6.4 
 ý 
b
thì khó 
  
 này.
Trong Flyweight mý 

  
               
(Hình 9.13).
Hình 9.13: 
  interface Character      m     
ConcreteCharacter     Character      Character
ConcreteCharacter riêng là vì tr 
Character.
public interface Character {
public void draw();
}

147
public class ConcreteCharacter implements Character{
private String symbol;
private String font;
public ConcreteCharacter(String s, String f){
this.symbol = s;
this.font = f;
}
public void draw() {
System.out.println("Symbol " + this.symbol + " with
font " + this.font );
}
}
import java.util.*;
public class CharacterFactory {
private Hashtable pool = new Hashtable<String, Character>();
public int getNum() {
return pool.size();
}
public Character get(String symbol, String fontFace) {
Character c;
String key = symbol + fontFace;
if ((c = (Character)pool.get(key)) != null) {
return c;
} else {
c = new ConcreteCharacter(symbol, fontFace);
pool.put(key, c);
return c;
}
}
}
//Lớp Test
import java.util.*;
public class Test {
public static void main(String[] agrs) {
CharacterFactory characterfactory = new
CharacterFactory();
ArrayList<Character> text = new
ArrayList<Character>();
text.add(0, characterfactory.get("a", "arial"));
text.add(1, characterfactory.get("b", "time"));
text.add(2, characterfactory.get("a", "arial"));
text.add(0, characterfactory.get("c", "arial"));
for (int i = 0; i < text.size(); i++){

148
Character c = (Character)text.get(i);
c.draw();
}
}
}
ý 
 
  
9.7 
9.7.1 
  quá trình  nó cho
  
 áp  
 Proxy c 
  
 t
     
nào 
   
remote proxy  
 khác.
 virtual proxy  
 protection proxy           

smart reference proxy 

9.7.2 
Hình 9.14 . 
Service: ó
RealService:  

Service
Proxy: 

149
Hình 9.14: Proxy
9.7.3 T 

thay vì theo .
Remote proxy) 
  (JVM)
Virtual proxy) 

Protection proxy) 
 Th 
thích  
  
 

protection proxy 
                 

i


9.7.4 
Image interface  
GIFImage JPGImage. 
Image 
nh 
 
 IF Image 
     không


150
Khi ImageProxy ImageImage
GIFImage hay JPGImage
 (Hình 9.15).
Hình 9.15: Proxy 
public interface Image {
public void process();
}
public class JPGImage implements Image {
public void process() {
System.out.print("JPG Image");
}
}
public class GIFImage implements Image {
public void process() {
System.out.print("GIF Image");
}
}
public class ImageProxy implements Image {
private Image image;
public void process() {
if (image == null)
image = new JPGImage();//tạo đối tượng ảnh JPG, chỉ
mang tính minh họa
image.process();
}
}

151
9.8 
 


khác.  ý 


1. 
2. 
3.  
trình
4.           
trình
5.    Address, s
 PhoneNum, tên Name          
Person  (Hình 9.15).
  

6.


152
7.          
trình
8. 

9. 

153
 VI






trung gian (mediator)
memento)



template method)
(behavior pattern)   
 mô hình
 hình cách  giúp chúng


 
 Template Method Interpreter. Template 

 
 


t vài

  thi 

 
ngang hàng 
  
 
                


154
trong 

 
MVC (Model/View/Controller) 

              



  
danh sách 



10
10
 
 
  .
10.1.2 

Handler

ConcreteHandler Handler
 Handler handlerMessage 
           handlerMethod  
Handler .
Hình 10.1: 

155
ng áp 
 
.
 .
 s

 khác p .
10.1.4 
  
hình dung    
tác  
khác. 
: tê
 d in ra các thông tin
                 
              
.
Hình 10.2: 
  TaskItem       Project       
Project  TaskItem
public interface TaskItem {
public TaskItem getParent();
public String getDetails();
public ArrayList getProjectItems();
}
public class Project implements TaskItem {

156
private String name;
private String details;
private ArrayList subtask = new ArrayList();
public Project(){ }
public Project(String newName, String newDetails){
name = newName;
details = newDetails;
}
public String getName(){
return name;
}
public String getDetails(){
return details;
}
public ProjectItem getParent(){
return null;
//vì project là ở mức cơ sở, đỉnh gốc trên cùng nên không có cha
}
public ArrayList getSubTask(){
return subtask;
}
public void setName(String newName){
name = newName;
}
public void setDetails(String newDetails){
details = newDetails;
}
public void addTask(TaskItem element){
if (!subtask.contains(element)){
subtask.add(element);
}
}
public void removeProjectItem(TaskItem element){
subtask.remove(element);
}
}
//Lớp Task thực thi giao tiếp TaskItem đại diện cho các tác vụ,
//các đỉnh không phải ở gốc của cây
public class Task implements TaskItem {
private String name;
private ArrayList subtask = new ArrayList();
private String details;
private TaskItem parent;

157
public Task(TaskItem newParent){
this(newParent, "", "");
}
public Task(TaskItem newParent, String newName, String
newDetails,){
parent = newParent;
name = newName;
details = newDetails;
}
public String getDetails(){
if (primaryTask){
return details;
}
else{
return parent.getDetails() + EOL_STRING + "\t" +
details;
}
}
public String getName(){
return name;
}
public ArrayList getSubTask(){ return subtask; }
public ProjectItem getParent(){
return parent;
}
public void setName(String newName){
name = newName;
}
public void setParent(TaskItem newParent){
parent = newParent;
}
public void setDetails(String newDetails){
details = newDetails;
}
public void addSubTask(TaskItem element){
if (!subtask.contains(element)){
subtask.add(element);
}
}
public void removeSubTask(TaskItem element){
subtask.remove(element);

158
}
}
//Lớp thực thi test mẫu
public class RunPattern {
public static void main(String [] arguments){
Project project = new Project(“Project 01”, “Detail of
Project 01”);
//Khởi tạo, thiết lập các tác vụ con …
detailInfor(project);
}
private static void detailInfor (TaskItem item){
System.out.println("TaskItem: " + item);
System.out.println(" Details: " + item.getDetails());
System.out.println();
if (item.getSubTask() != null){
Iterator subElements = item.getSubTask().iterator();
while (subElements.hasNext()){
detailInfor ((TaskItem)subElements.next());
}
}
}
}
10.2 
10.2.1 





  

Command  thi các
Execute trên
Command -

Execute 
 cách  menu, menuItem gán
menuItem Command. 
menuItemcommand.execute() command  
Command. Hàm execute() 
Command 

159
danh sách 
nhau.
10.2.2 

CommandInvoker 
Invoker Command
ReceiverCommand 

ConcreteCommand 
Receiver 
Hình 10.3: Command
:
Hình 10.4: 
  . 
Command  ConcreteCommand). 
executeCommand()   
. Invoker executeCommand() 
execute()  . 
 doAction()      doAction()


160
10.2.3 
M:



 
 
thi 

  


               
 


.
M             



10.2.4 

public interface Command{
public void execute();
}
public class ConcreteCommand implements Command{
private Receiver receiver;
public void setReceiver(Receiver receiver){
this.receiver = receiver;
}
public Receiver getReceiver(){
return this.receiver;
}
public void execute (){
receiver.doAction();
}
}

161
public class Receiver{
private String name;
public Receiver(String name){
this.name = namel
}
public void doAction(){
System.out.print(this.name + “ fulfill request!”);
}
}
public class Invoker{
public void executeCommand(Command command){
command.execute();
}
}
public class Run{
public static void main(String[] agrs){
Command command = new ConcreteCommand();
command.setReceiver(new Receiver(“NguyenD”));
Invoker invoker = new Invoker();
Invoker.executeCommand(command);
}
}
10.3 ITERATOR
10.3.1 
  
, 
 tiêu chí k 
List 
  
  Iterator 

        Iterator      
không 

10.3.2 

sách, Container  Container 
 NameIteratorDemo NameRepository 

162
Hình 10.5: Iterator

Truy nh






Iterator  Memento. 
 



public interface Iterator {
public boolean hasNext();
public Object next();
}
public interface Container {
public Iterator getIterator();
}
ublic class NameRepository implements Container {
public String names[] = {"Minh" , "Ngoc" ,"Thanh" , "Lan"};
@Override

163
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
if(index < names.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
public class IteratorPatternDemo {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for(Iterator iter = namesRepository.getIterator();
iter.hasNext();){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}
10.4 
10.4.1 

 
 

164
V và
  
  
thu 
Interpreter 
  câu            
In

10.4.2 
  cho trong Hình 10.6. 
Expression: 
TerminalExpression:  Expression

NonterminalExpression:  Expression

Expression .
Context: 
 Expression.
Client:  
TerminalExpression NoterminalExpression


Hình 10.6: Interpreter
10.4.3 






165




               
In

10.4.4 
n y con:

cây và 
Hình 10.

Hình 10.8: 
import java.util.Stack;
public class Context extends Stack<Integer>{
}
public interface Expression {
public void interpret(Context context);
}

166
public class TerminalExpressionNumber implements Expression {
private int number;
public TerminalExpressionNumber(int number){
this.number = number;
}
public void interpret(Context context) {
context.push(this.number);
}
}
public class TerminalExpressionPlus implements Expression {
public void interpret(Context context) {
//Cong 2 phan tu phia tren dinh Stack
context.push(context.pop() + context.pop());
}
}
public class TerminalExpressionMutil implements Expression{
public void interpret(Context context) {
//Nhan 2 phan tu phia tren dinh Stack
context.push(context.pop() * context.pop());
}
}
//
import java.util.ArrayList;
public class NonterminalExpression implements Expression {
private ArrayList<Expression> expressions;//tham chieu den
mang Exoression con
public ArrayList<Expression> getExpressions() {
return expressions;
}
public void setExpressions(ArrayList<Expression>
expressions) {
this.expressions = expressions;
}
public void interpret(Context context) {
if (expressions != null){
int size = expressions.size();
for (Expression e : expressions){
e.interpret(context);
}
}
}
}
//
import java.util.*;

167
public class Client {
public static void main(String[] agrs){
Context context = new Context();
// 3 3 *
ArrayList<Expression> treeLevel1 = new
ArrayList<Expression>();
treeLevel1.add(new TerminalExpressionNumber(3));
treeLevel1.add(new TerminalExpressionNumber(3));
treeLevel1.add(new TerminalExpressionMutil());
// 5 (3 3 *) +
ArrayList<Expression> treeLevel2 = new
ArrayList<Expression>();
treeLevel2.add(new TerminalExpressionNumber(5));
Expression nonexpLevel1 = new NonterminalExpression();
((NonterminalExpression)nonexpLevel1).setExpressions(treeLevel1);
treeLevel2.add(nonexpLevel1);
treeLevel2.add(new TerminalExpressionPlus());
// (5 (3 3 *) +) 6 +
ArrayList<Expression> treeLevel3 = new
ArrayList<Expression>();
Expression nonexpLevel2 = new NonterminalExpression();
((NonterminalExpression)nonexpLevel2).setExpressions(treeLevel2);
treeLevel3.add(nonexpLevel2);
treeLevel3.add(new TerminalExpressionNumber(6));
treeLevel3.add(new TerminalExpressionPlus());
for(Expression e : treeLevel3){
e.interpret(context);
}
if (context != null)
System.out.print("Ket qua: " + context.pop());
}
}
10.5 
10.5.1 
ng khuy 
   nhi
 
nhau. Mediator 

 .

168
u Mediator 
- 
-  . 
  và t
 bên  thay

10.5.2 
Hình 10.9: Mediator
 
Mediator (IChatroom):      cho các    
ConcreteMediator (Chatroom) 
colleague và xcolleague
Colleague classes (Participant) m  Colleague     
Mediator colleague mediator khi
colleague khác.
10.5.3 
 
 
 

khác.                

Mediator khác 

 
, Mediator cho phép các hành vi

 

169
10.6 
10.6

, 

bên 

u khi  
 
memento do 
 

10.6.2 
Hình 10.10: Memento

Memento: l Originator b
Originator.
Originator:  s

Caretaker: t


g 
sau y. 
 
ho các thao tác có




170
 

g

Chi p 
 
 
memento.
10.7 



kia.  - i
 
10.7.2 

Subject: h


ConcreteSubject: 
r  
Observer: 

ConcreteObserver: 
lc 

Hình 10.11: Observer

171

 

10.8 
10.8.1 



 




 


10.8.2 


Context , nó duy 
 
State: 

ConcreteState (RedState, SilverState, GoldState) 


Flyweight   các
c Singleton.

172
10.9 




chiến lược strategy đối tượng chiến lược đối tượng ngữ cảnh

 nh 




.
10.9.2 
Hình 10.13: Strategy

Strategy: Khai  toán 

          toán     
ConcreteStrategy.
ConcreteStrategy (QuickSort, ShellSort, MergeSort): toán
 
Nó d.



10.10.1 
(Template Method) 


173
                 
phương thức khung lớp khung (Template class) 
     

10.10.2 

AbstractClass:  c thao tác y
 toán. 
ethod()  toán. templateMethod()
               

ConcreteClass:  ra
 toán.
Hình 10.14: Template method

  :
 toán 

Khi  

 ,
 t

 
toán. Các 
toán.
10 VISITOR

nh khung 


174
10.11.2 
Visitor: 
 



ConcreteVisitor:  



Element:            

ConcreteElement:   visitor

ObjectStructure:  
cao cho phép vis 


175
Hình 10.15: Visitor
10.11.3 

 
  





hao tác này vào
.

176



Các 

10.12 
Trong 
  các
  
    


1. y
2. 
3. 

4. 



ý


a. 
b. àng

5. ý 
ý 
6. ý ý 
ýý.
7. ý 

1: CASE STUDY
177

trình 



11.1 CASE STUDY 1:  
 
 . Các

API cho p
trong 


u
 
T : http://www.oracle.com/java/dataaccessobject.html
11.1.1  
BusinessObject: 
 các bean 
 
DataAccessObject:  


cho DataAccessObject.
DataSource

TransferObject: 



1: CASE STUDY
178
Hình 11.1
 .
Hình 11.2: B
 Factory Method (Hình 11.3).
1: CASE STUDY
179
Hình 11.3
gFactory method (Hình 11.4)
Hình 11.4: B
 khách hàng
.    cho
trong Hình 11.5
1: CASE STUDY
180
Hình 11.5: B
 (Hình 11.6)
Hình 11.6

// Abstract class DAO Factory
public abstract class DAOFactory {
// List of DAO types supported by the factory
public static final int CLOUDSCAPE = 1;
public static final int ORACLE = 2;
public static final int SYBASE = 3;
...
// There will be a method for each DAO that can be
// created. The concrete factories will have to
// implement these methods.
public abstract CustomerDAO getCustomerDAO();
public abstract AccountDAO getAccountDAO();
public abstract OrderDAO getOrderDAO();
...
public static DAOFactory getDAOFactory(
1: CASE STUDY
181
int whichFactory) {
switch (whichFactory) {
case CLOUDSCAPE:
return new CloudscapeDAOFactory();
case ORACLE :
return new OracleDAOFactory();
case SYBASE :
return new SybaseDAOFactory();
...
default :
return null;
}
}
}
//Hiện thực hóa cài đặt DAOFactory cho Cloudscape
import java.sql.*;
public class CloudscapeDAOFactory extends DAOFactory {
public static final String DRIVER=
"COM.cloudscape.core.RmiJdbcDriver";
public static final String DBURL=
"jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
// method to create Cloudscape connections
public static Connection createConnection() {
// Use DRIVER and DBURL to create a connection
// Recommend connection pool implementation/usage
}
public CustomerDAO getCustomerDAO() {
// CloudscapeCustomerDAO implements CustomerDAO
return new CloudscapeCustomerDAO();
}
public AccountDAO getAccountDAO() {
// CloudscapeAccountDAO implements AccountDAO
return new CloudscapeAccountDAO();
}
public OrderDAO getOrderDAO() {
// CloudscapeOrderDAO implements OrderDAO
return new CloudscapeOrderDAO();
}
...
}
//Cài đặt DAO Interface cho Customer
public interface CustomerDAO {
public int insertCustomer(...);
public boolean deleteCustomer(...);
public Customer findCustomer(...);
1: CASE STUDY
182
public boolean updateCustomer(...);
public RowSet selectCustomersRS(...);
public Collection selectCustomersTO(...);
...
}
// Cài đặt Cloudscape DAO cho Customer
// CloudscapeCustomerDAO implementation of the
// CustomerDAO interface. This class can contain all
// Cloudscape specific code and SQL statements.
// The client is thus shielded from knowing
// these implementation details.
import java.sql.*;
public class CloudscapeCustomerDAO implements CustomerDAO {
public CloudscapeCustomerDAO() {
// initialization
}
// The following methods can use
// CloudscapeDAOFactory.createConnection()
// to get a connection as required
public int insertCustomer(...) {
// Implement insert customer here.
// Return newly created customer number
// or a -1 on error
}
public boolean deleteCustomer(...) {
// Implement delete customer here
// Return true on success, false on failure
}
public Customer findCustomer(...) {
// Implement find a customer here using supplied
// argument values as search criteria
// Return a Transfer Object if found,
// return null on error or if not found
}
public boolean updateCustomer(...) {
// implement update record here using data
// from the customerData Transfer Object
// Return true on success, false on failure or
// error
}
public RowSet selectCustomersRS(...) {
// implement search customers here using the
// supplied criteria.
1: CASE STUDY
183
// Return a RowSet.
}
public Collection selectCustomersTO(...) {
// implement search customers here using the
// supplied criteria.
// Alternatively, implement to return a Collection
// of Transfer Objects.
}
...
}
//Customer Transfer Object
public class Customer implements java.io.Serializable {
// member variables
int CustomerNumber;
String name;
String streetAddress;
String city;
...
// getter and setter methods...
...
}
//Sử dụng DAO và DAOFactory ở client code
...
// create the required DAO Factory
DAOFactory cloudscapeFactory =
DAOFactory.getDAOFactory(DAOFactory.DAOCLOUDSCAPE);
// Create a DAO
CustomerDAO custDAO =
cloudscapeFactory.getCustomerDAO();
// create a new customer
int newCustNo = custDAO.insertCustomer(...);
// Find a customer object. Get the Transfer Object.
Customer cust = custDAO.findCustomer(...);
// modify the values in the Transfer Object.
cust.setAddress(...);
cust.setEmail(...);
// update the customer object using the DAO
custDAO.updateCustomer(cust);
// delete a customer object
custDAO.deleteCustomer(...);
// select all customers in the same city
Customer criteria=new Customer();
criteria.setCity("New York");
1: CASE STUDY
184
Collection customersList =
custDAO.selectCustomersTO(criteria);
// returns customersList - collection of Customer
// Transfer Objects. iterate through this collection to
// get values.
...
11.2 CASE STUDY 2: BOOKSTORE
h bày áp   Façade, Observer v
  Bookstore.
Áp dụng Observer
Hình 11.7  Observer cho Bookstore
Áp dụng Factory
Hình 11.8  Factory cho Bookstore
Áp dụng Façade
1: CASE STUDY
185
Hình 11.9:  cho Bookstore
1: CASE STUDY
186

package entity;
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.validation.constraints.Null;
@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String author;
private String state;
private Boolean status;
private Integer price;
private String image;
private int quanity;
private String description;
@OneToMany(mappedBy = "book", cascade= CascadeType.REMOVE)
private List<BookObserver> booksObserver = new
ArrayList<BookObserver>();
1: CASE STUDY
187
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public void attach(BookObserver bo) {
if (bo == null) {
throw new NullPointerException("Null Observer");
}
if (!booksObserver.contains(bo)) {
booksObserver.add(bo);
}
}
private boolean changes = false;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) id;
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the
id fields are not
set
if (!(object instanceof Book)) {
return false;
1: CASE STUDY
188
}
Book other = (Book) object;
if (this.id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Book[ id=" + id + " ]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public List<BookObserver> getBooksObserver() {
return booksObserver;
}
public void setBooksObserver(List<BookObserver> booksObserver) {
this.booksObserver = booksObserver;
}
public String getState() {
return state;
}
public void setState(String state) {
if (this.state == null) {
1: CASE STUDY
189
this.state = state;
} else if (!this.state.equals(state)) {
this.changes = true;
}
this.state = state;
notifyObservers();
}
public void notifyObservers() {
for (BookObserver observer : booksObserver) {
observer.update();
}
}
public Boolean isStatus() {
return status;
}
public void setStatus(Boolean status) {
if (this.status != null) {
changes = true;
if (status == false) {
setState("Het Hang");
} else {
setState("Co Hang");
}
System.out.println("ok");
}
this.status = status;
System.out.println("not ok");
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
if (this.price != null) {
this.changes = true;
1: CASE STUDY
190
if (this.price < price) {
setState("Tang gia " + (price - this.price));
} else if (this.price == price) {
changes=false;
} else {
setState("Giam gia " + (this.price - price));
}
}
this.price = price;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public int getQuanity() {
return quanity;
}
public void setQuanity(int quanity) {
this.quanity = quanity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
1: CASE STUDY
191
}
public boolean isChanges() {
return changes;
}
public void setChange(boolean changes) {
this.changes = changes;
}
}
package entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class BookObserver implements Observer,Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String message;
@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
public BookObserver(Book book) {
this.book = book;
this.book.attach(this);
}
public int getId() {
return id;
}
public void setId(int id) {
1: CASE STUDY
192
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public BookObserver() {
}
@Override
public void update() {
if(book.isChanges()){
this.message = book.getState();
}
}
@Override
public void setBook(Book book) {
this.book = book;
}
public Book getBook() {
return book;
}
}
package entity;
import entity.OrderDetail;
import java.util.List;
public class ShipMienBac extends Shipment{
@Override
public int calculateShipmentPayment() {
int gia = 0;
for(OrderDetail ct : books){
gia +=ct.getQuanity()*5;
1: CASE STUDY
193
}
return gia;
}
}
package entity;
import java.util.List;
public class ShipMienTrung extends Shipment{
@Override
public int calculateShipmentPayment() {
int gia = 0;
for(OrderDetail ct : books){
gia +=ct.getQuanity()*10;
}
return gia;
}
}
package entity;
import java.util.List;
public class ShipMienNam extends Shipment{
@Override
public int calculateShipmentPayment() {
int gia = 0;
for(OrderDetail ct : books){
gia +=ct.getQuanity()*15;
}
return gia;
}
}
package entity;
import entity.OrderDetail;
import java.io.Serializable;
import java.util.List;
1: CASE STUDY
194
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public abstract class Shipment {
public Shipment() {
}
protected List<OrderDetail> books;
public abstract int calculateShipmentPayment();
public List<OrderDetail> getBooks() {
return books;
}
public void setBooks(List<OrderDetail> books) {
this.books = books;
}
}
package session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
1: CASE STUDY
195
getEntityManager().remove(getEntityManager().merge(entity));
}
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q =
getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq =
getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt =
cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q =
getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}}
package session;
import entity.BookObserver;
1: CASE STUDY
196
import java.util.List;
import javax.ejb.Local;
@Local
public interface BookObserverFacadeLocal {
void create(BookObserver bookObserver);
void edit(BookObserver bookObserver);
void remove(BookObserver bookObserver);
BookObserver find(Object id);
List<BookObserver> findAll();
List<BookObserver> findRange(int[] range);
int count();
}
package session;
import entity.BookObserver;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class BookObserverFacade extends
AbstractFacade<BookObserver> implements BookObserverFacadeLocal {
@PersistenceContext(unitName = "BookStorePU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public BookObserverFacade() {
super(BookObserver.class);
}
}
package session;
import entity.OrderDetail;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
1: CASE STUDY
197
import javax.persistence.PersistenceContext;
@Stateless
public class OrderDetailFacade extends AbstractFacade<OrderDetail>
implements OrderDetailFacadeLocal {
@PersistenceContext(unitName = "BookStorePU")
private EntityManager em;
@Override
protected EntityManager getEntityManager() {
return em;
}
public OrderDetailFacade() {
super(OrderDetail.class);
}
}
 ervlet và trang JSP  

198

[1] S. T. Albin, The Art of Software Architecture: Desing Methods and Techniques, John
Wiley and Sons, 2003.
[2]  và C++

[3] Bass L., Clements P., Kazman R., Software Architecture in Practice, Addison-
Wesley, 2013
[4] A. Dennis B. H. Wixom and David Tegarden, System Analysis and Design with
UML version 2.0: An Object-Oriented Approach, Second Edition, John Wiley &
Sons 2005.
[5] M. K. Debbarma et al., A Review and Analysis of Software Complexity Metrics in
Structural Testing, International Journal of Computer and Communication
Engineering, Vol. 2, No. 2, March 2013. Available at
http://www.ijcce.org/papers/154-K271.pdf
[6] Gregor Engels, Object-Oriented Modeling: A Roadmap, http://wwwcs.uni-
paderborn.de/cs/ag-engels/Papers/2000/EG00objectorientedModelling.pdf
[7] Hans-Erit, Magnus Penker, Brian Lyons, David Faado, UML2 Toolkit, Wiley Publishing,
Inc, 2004
[8] Microsoft, Microsoft application architecture guide, Second Edition, 2009
[9] E. Gamma, R. Helm, R. Johnson, J. Vlissides, Design patterns: Elements of
Reusable Object Oriented Software, Addition Wesley, 1994
[10] Partha Kuchana, Software architecture design patterns in Java, Auerbach
Publications, 2004.
[11] Lin Liao, From Requirements to Architecture: The State of the Art in Software
Architecture Design. Availble at:
http://www.liaolin.com//Courses/architecture02.pdf
[12]  , Object-Oriented Analysis and Design: Understanding System
Development with UML 2.0, John Wiley & Sons, 2005.
[13]        -Hill,
2005
[14] 
 
[15] S. Schach, Object-oriented and classical software engineering, Eighth Edition,
McGraw-Hill, 2011.
[16] Brett Spell, Pro Java Programming, Second Edition, Apress 2006

199
[17] Ashish Sharma and D.S. Kushwaha, A Complexity measure based on Requirement
Engineering Document, Journal of computer science and engineering, Vol.1, Issue
1, May 2010. Available at http://arxiv.org/ftp/arxiv/papers/1006/1006.2840.pdf
[18] R. Taylor, N. Medvidovic and E. Dashofy, Software Architecture: Foundations,
Theory and Practice, Wiley Publisher, 2010.
[19] David P. Tegarden et al., A Software Complexity Model of Object-Oriented
Systems, 1992. Available at http://www.acis.pamplin.vt.edu/faculty/tegarden/wrk-
pap/DSS.PDF
[20] Joseph S. Valacich, Joey F. George, Jeffrey A. Hoffer, Essentials of systems analysis
and design, Fifth Edition, Pub. Pearson, 2011.
[21] A. J. A. Wang and K. Qian. Component Oriented Programming, Wiley, 2005
[22] Java Pattern:
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
[23] Java Pattern Tutorial: https://www.tutorialspoint.com/design_pattern/index.htm
| 1/210

Preview text:

Temperature Converter

Enter a degree to convert:

value="Fahrenheit to Centigrade"> 80

CHƢƠNG 5: MÔ HÌNH THÀNH PHẦN PHẦN VỚI EJB
value="Centigrade to Fahrenheit"> <%
DecimalFormat twoDigits = new DecimalFormat ("0.00");
String degree = request.getParameter("degree");
if ( degree != null && degree.length() > 0 ) {
double d = Double.parseDouble(degree); %> <%
if (request.getParameter("fToC") != null ) { %>

<%= degree %> fahrenheit degrees are
<%= twoDigits.format(converter.fToC(d)) %> centigrade degrees. <% } %>
<% if (request.getParameter("cToF") != null ) { %>

<%= degree %> centigrade degrees are
<%= twoDigits.format (converter.cToF(d)) %> fahrenheit degrees . <% } %> <% } %>