Compare commits
145 Commits
Author | SHA1 | Date | |
---|---|---|---|
ba7142ca97 | |||
2f33094030 | |||
193879dff6 | |||
6848dd020e | |||
7db7df38fd | |||
aa1f57a253 | |||
683b45d1b0 | |||
e80677b1f3 | |||
a2a08a3a3e | |||
fb4c0f77e5 | |||
99de0e1644 | |||
dba2d8aef7 | |||
06b5c671f5 | |||
c63494cef2 | |||
7f9789ce1d | |||
5d8d312733 | |||
a59e0fa961 | |||
c9f4048301 | |||
d8ac00536c | |||
eb36033b83 | |||
acaccc1c53 | |||
06ba337b90 | |||
1b0f55c3eb | |||
286f187df4 | |||
e9579633da | |||
91048a49b4 | |||
fb3a998c04 | |||
711f3faf67 | |||
44e4b3c803 | |||
c5b9c63b39 | |||
c89bf0eb44 | |||
6d3dce065d | |||
d0ad0f7ea9 | |||
a0c081f5ea | |||
b7dbb4049c | |||
87d4853846 | |||
5836fdb54b | |||
f38119c565 | |||
5828ef9dd1 | |||
6a560f7d15 | |||
2e90f82cab | |||
f9d1e9aa3f | |||
7ca5342819 | |||
263534caab | |||
8652d0d32b | |||
a8f2e70e0a | |||
4e290416df | |||
565d5a0129 | |||
50d7dbe4de | |||
5f9100cd03 | |||
2cf773e550 | |||
05629f687b | |||
c13661810e | |||
bd4247e864 | |||
a745c5d8ce | |||
efc6eb8828 | |||
9d2f0c6c71 | |||
c6354c48bb | |||
6c9e005a79 | |||
d8e779a7b2 | |||
f439673de0 | |||
a3324a122c | |||
f28ed7b46e | |||
7f1fac036e | |||
08cc50e875 | |||
b7767b376d | |||
f0a1af0c46 | |||
81f4df9a32 | |||
f80d917432 | |||
1dc038bc30 | |||
6f1736d2e6 | |||
2a98a1399e | |||
a5ec376089 | |||
82d7e57e8e | |||
671230d798 | |||
ed1a0022b9 | |||
5db6776971 | |||
fbf5ffe67a | |||
51751ec821 | |||
f47dc1eb7c | |||
2a7feba427 | |||
68d094a847 | |||
e367e48ec2 | |||
b639f3630e | |||
f9789d6926 | |||
4a81453da4 | |||
b62d431d62 | |||
8525bfd323 | |||
9c088b5f47 | |||
3eab4d75a6 | |||
f6c8bfbc39 | |||
a1a4088087 | |||
cbba487ff8 | |||
37b9d45a74 | |||
2e99cb41ad | |||
eb2a232382 | |||
4b3435c550 | |||
fba30e59ee | |||
2d750dc0fd | |||
002774b5aa | |||
2150a2bb55 | |||
746e452c2b | |||
600553ec0f | |||
64824d65aa | |||
bfbc8fd740 | |||
df9be78504 | |||
229fda9f3c | |||
148de06bb1 | |||
67d4477d25 | |||
db10b937f2 | |||
1474a50e5e | |||
9f612ecfda | |||
0271e55983 | |||
54d8ec94be | |||
ffbf56f01a | |||
83fcbe0713 | |||
0982f00a61 | |||
871df4f918 | |||
7ae9e3ee22 | |||
c572fe885e | |||
a221245909 | |||
8bf4497879 | |||
8073b93182 | |||
9b1a9aafc1 | |||
c6b6c8123f | |||
87c10faaac | |||
d1b11539ec | |||
c744bf418a | |||
5873aeeb69 | |||
d8919d88f0 | |||
b67719ab32 | |||
a8f50297eb | |||
3128d3fb40 | |||
a2dba5bf6d | |||
40c00ca2af | |||
8e25ec55bf | |||
8881950e6d | |||
51bcee5d7d | |||
15a25f0ef3 | |||
f3902ffc16 | |||
8208f6252b | |||
ca73621f4d | |||
4e9988877a | |||
ac721c695c | |||
24f258848c |
1
.gitignore
vendored
@ -17,3 +17,4 @@ datanucleus.log
|
||||
/bin/
|
||||
*.log
|
||||
data-mapper/src/main/resources/log4j.xml
|
||||
event-sourcing/Journal.json
|
||||
|
@ -36,4 +36,4 @@ notifications:
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: never # options: [always|never|change] default: always
|
||||
|
||||
sudo: false # route the build to the container-based infrastructure for a faster build
|
||||
sudo: required
|
@ -1,190 +0,0 @@
|
||||
parent: half-sync-half-async; artifact: half-sync-half-async
|
||||
Puml Server ID: RScv3SCm3030LU819FRPXg5fIm552tnYPFiyjRi3RkbAaYkdoQr5JBy369vrxz7oaSv6XmPhL3e6TCaJ0msU-CAoilTToyG8DdKOw5z0GzcAlvNAN_WZSD1brBHHPmxv0000
|
||||
parent: abstract-document; artifact: abstract-document
|
||||
Puml Server ID: PSjB3eCm34NHhPG599vtDyQn85L-ifzX-p3lxEf8Twj3MXGDQvyJMFubChxpKN767gucSq07iinEjSNDOACVNvoAUZr6MWoe3QVE_WRnxZ0Mf38b-hkIGlurX_MyehS7
|
||||
parent: tolerant-reader; artifact: tolerant-reader
|
||||
Puml Server ID: NSZ14SCm20NHLf829ExfXaYChGn26lZ4xSVdtFRjSrZJx9AkZnFOyI9olkenSEOxGxmjWnXgMvE6viLWfmz_kNI9SLZP38XRqEIuWx1Kd0t5XVjjGVj_DNtMdLD_
|
||||
parent: event-driven-architecture; artifact: event-driven-architecture
|
||||
Puml Server ID: TOhH3SCW30LNQGS0_tSRnrZ15H1adfFromBzkfFktZQaHT7mzgh0N1yYvoUVXXf7B7Mv1dGWozN9MZmCTlhopQdeidEaoO3wMDHvRI6zzvwAssPYbsfGGRYIGlxN7DxpZDv-
|
||||
parent: publish-subscribe; artifact: publish-subscribe
|
||||
Puml Server ID: PSZB3SCm203GLTe1RExT1XCKKs5YyMdMR--zFRsd66aTNAwFcRdZ1U1uzrDorgXWfykIBJjT2qJhnaI7Dtwm7HnoMjkOoMu12-C7s3LKOhQe4UGo63ZfVtlvwhkMVW40
|
||||
parent: facade; artifact: facade
|
||||
Puml Server ID: BSP15eCm20N0gxG7CEoz3ILKqvTW7dpq-hhehERTJ7fMJU-l7PYn4ZbVPMlOyvEXBeT13KMEGQtdnM2d7v-yL8sssJ8PKBUWmV64lYnSbHJoRqaVPUReDm00
|
||||
parent: service-locator; artifact: service-locator
|
||||
Puml Server ID: NSjB3iCm203HgxG7iDdtDeIWX0fZYqzo_MRTtUX9ynOZhPtBzNLchlW0EDxza3nhgs2dQScMdUO0qRenqU6B5xQTGmvh2pFPBM1WF07FSmbnqqcOqu6J_gsNZxvgw0y0
|
||||
parent: dao; artifact: dao
|
||||
Puml Server ID: 5SR14OKW30N0LhG0oVrt4o6ZE12Ov4NR_thQNQlc5aN2sd82qtz4naywAixOmyNoK8WYvT6fjdWOR7JnpLiHhuTkam4nTUhiRwZm847-J64zpUZj3m00
|
||||
parent: model-view-presenter; artifact: model-view-presenter
|
||||
Puml Server ID: ROlR3SGW3C1MkGu0-RzjKeXQJWcWFChwPO3xispvQBrmL0hbp-q-xGkWkFBL_8upZBICxjGzbo7GE1OwAlpmmLJ9sjNJH7VIRY1e6q169KvFevMcakrtI_BoD-HGoJE4Nm00
|
||||
parent: observer; artifact: observer
|
||||
Puml Server ID: FSkn4OGm30NHLg00hFow4KO3PcpP8tr1-pYwx6smQz5Suv2mkbp0y1-HyPlEWYlsSB7S5Q98kJSgDLu66ztyy7Q8brEtmO2OEZNs2Uhxl9u9GVv72cjfHAiV
|
||||
parent: intercepting-filter; artifact: intercepting-filter
|
||||
Puml Server ID: RSfB3i8m303Hgy014k-vZN5DQkIuaJ_q-fGzkz7JtCL8Q-DolUsPAnu0ZcSVadizAzZfi6JBJiS4qJenqU6D7smRXmnh2pFPBM1YN05o_KwyKcoqb-ZFEEcVz_BPLqtz0W00
|
||||
parent: factory-method; artifact: factory-method
|
||||
Puml Server ID: NSZB3G8n30N0Lg20n7UwCOxPP9MVx6TMT0zdRgEvjoazYeRrMmMsFuYChtmqr7Y6gycQq8aiQr3hSJ7OwEGtfwBUZfas0shJQR3_G2yMBFkaeQYha4B-AeUDl6FqBm00
|
||||
parent: private-class-data; artifact: private-class-data
|
||||
Puml Server ID: RShR3SCm243HLTe1RFwx3S4eeSB4uf6itmpGlwkZ-nOZhS7b-ZeoLtm07E--InwrLR3JQScMdSu9edLZeiCNBso3GtPh2pFPBM1YF07BvSBaHeeHRJm_SD8VxkMphvhw0m00
|
||||
parent: async-method-invocation; artifact: async-method-invocation
|
||||
Puml Server ID: TSdB3SCW303GLTe1mFTkunWhk0A3_4dKxTi5UdlIUuhIoCPfuz4Zjhy03EzwIlGyqjbeQR16fJL1HjuOQF362qjZbrFBnWWsTPZeFm3wHwbCZhvQ4RqMOSXIuA1_LzDctJd75m00
|
||||
parent: execute-around; artifact: execute-around
|
||||
Puml Server ID: NSZ14G8n20NGLhI0XBlT865suoGa0n_NylNixSsxTvEHJTF7xGHsF8YShtfqdFdCK9TbK4ELDQcFl1ZizE8tbwRH3okR0NKBcXm_a7vK4bhOLreZXVnLJPzrvnnV
|
||||
parent: monostate; artifact: monostate
|
||||
Puml Server ID: HSV14OGm20NGLjO23FVj1YEZsGaa0nzjVxrvUszfLdlkaju_9p3ZI-HybwFXp2r3l0w364eTIgtdpM2d7r-yxXBji7Ko86v1ol60TDW8C8G4zLr9rp9J-ny0
|
||||
parent: thread-pool; artifact: thread-pool
|
||||
Puml Server ID: JSV14SCW30J0Lk82GFzq8uF6a1624IUx_UIPt-xHhMXK2TTN0zP-4pa_-UfeSSOMBzCWXbpceAxnCDZfmpUdAhjVbXO3uhPfyFw1q5oufZMdag3yFuUFl6Be5m00
|
||||
parent: delegation; artifact: delegation
|
||||
Puml Server ID: JSV14GCX20NGLf82LkxfXbN69OFeu2VRVdBCxRsdUhLiac6F2rZxHHHybwwuyimjKQT37ANEGMfvCpZepHy-ccpjVYm697pJuFq3DJ7f39rEWlhNaZ7Aoc5V
|
||||
parent: chain; artifact: chain
|
||||
Puml Server ID: 9SR13SCm20NGLTe1OkxTXX0KKzd4Wa-pVYlrdTxJN4OTMZ4U7LZv8Wg-ssdejLTgoELGHvDhaesw6HpqvWzlXwQTlYq6D3nfSlv2qjcS5F9VgvXjrHnV
|
||||
parent: resource-acquisition-is-initialization; artifact: resource-acquisition-is-initialization
|
||||
Puml Server ID: ZShR3S8m343HLUW0YV_PnhXMQvGumOzMOdhA1lqxkhgBABLSEQqzzeZfJm33isuIUxxIsMXei4QbqK5QdXXeyCO3oyekcvQ94MpgqD4lWB6FDEA2z4bn2HbQn8leHMponNy13hgvrhHUP_Rs0m00
|
||||
parent: fluentinterface; artifact: fluentinterface
|
||||
Puml Server ID: NOj93eCm302_KXv0VEzlN6F0bMCYB_3zvjpRQ3IpY97MnkNwEZD7l04SdtP8dlMfOAVBaYqRNHr4wy54Xo_Uk6uSSjWwC9FT0Zh61DYrPY_pyXs9WPF-NIllRLJN7m00
|
||||
parent: service-layer; artifact: service-layer
|
||||
Puml Server ID: LOl93SCm3C1MQGUmzUysgY8aAcJ5q96WszVV_aW2V8gHriRb-ZWoPxm07E--Inxrhc2dqv8jEvq3HEl6H8SFNjWs3jcjJSnaju21iG3MSmbnK_mkuwJ_qij7dpNq1m00
|
||||
parent: visitor; artifact: visitor
|
||||
Puml Server ID: DSR14OGm20NGLhG0mtsxmSWeJa8oyD7sTo_xJczLgoqFIM_B1Spu43c_vLHSkMU8rs4GGwcZaxPy6UnqyyFR8Q6dRPC1SGlg7B_Gew4OJeBwVqdlPMPlNm00
|
||||
parent: double-dispatch; artifact: double-dispatch
|
||||
Puml Server ID: NSbB3iCW303HgpG70Ezx6yTOWSeOv4zp_MRTtUZDCPGa6wV9gqTiVmCOtlKQqVDCPwEbmHgLreGXUMEWmGU_M1hxkBHiZ61JXud-1BILft1fmvz37JZetshQh3kd_000
|
||||
parent: monad; artifact: monad
|
||||
Puml Server ID: 9SR13SCm20NGLPe1OkxTXjWeSMMm1Pza_LRgExsjMntP97syBc35cyZvAMV7bKU6U9q6CPGwbVh8Xy5E7xvvRnBzj7qn86v1ol4BwJHk9AZ_bNGjAtLy0G00
|
||||
parent: front-controller; artifact: front-controller
|
||||
Puml Server ID: PSlB3OGm303HLfO24j-t6nCC13bEvC_IFk6yjz6JPgbIE3OAvS_fFkmBe7Zde_ePQnXfwU8adajlK3bkT5Iuy8Tf8wk7f87kf6BGq6R0hlD8xwQTUG9v-SCSslA8nWy0
|
||||
parent: strategy; artifact: strategy
|
||||
Puml Server ID: FSV13OCm30NGLM00udktCS4AGOaJsTz5tRwSkBstLiqj3WbhombC_n0PtwbKdB67Y-MX44NAerDjSJFOwE8lRuTuBRfD1iJKgRC_88SnfFn8aD-ai9vczFO7
|
||||
parent: command; artifact: command
|
||||
Puml Server ID: DSgn4OCm30NGLM00h3xR25i7vYpXaxx2-g59zugtTgiZcwIFvGHcV8YSdt9qdBbdYDVR88PIRwK-yc6mqyLVtff4FsoR38XRa7Aye3SgMoD1_RkaQvcfumS0
|
||||
parent: abstract-factory; artifact: abstract-factory
|
||||
Puml Server ID: PSZB3OD034NHLa81Czwd6sCC39gVxEUWT1_ssLmTtQLqgR5fM7sTmFGtaV6TZu8prd0r6HtQaMKqAZLk1XjT_E6qgPUZfyc0MdTgx0-8LuUn8ErFXdr98NypXxKyezKV
|
||||
parent: flux; artifact: flux
|
||||
Puml Server ID: 7SP14eCm20NGg-W13FlU1YFLE0GpyAazVZk-rPkRLSrDqdKwW14l8kUxx0r7hXdYzJA8eTIhKzEy6UnqyeUNJQBjjWm6n2seS_n3Ryql2UgJajxBoAu_
|
||||
parent: event-aggregator; artifact: event-aggregator
|
||||
Puml Server ID: PSf13iCW30NHgxG70Ezx6uTOX0eCih-JwvTzTwEdUJSjFKu9wwyBMFuXCdvoRRZY21ShKo6ANEQWrkDXiD6NRqwdUAkQ5WDYwZJOTv3SUqzSgqbbp0qeVvZ3Hbun-Wy0
|
||||
parent: singleton; artifact: singleton
|
||||
Puml Server ID: HSV14SCm20J0Lk82BFxf1ikCh0n26ZZizfDVVhjRjwfvIhg-Bc35cyZvAQtZoYD3l4w364gTWxhcms2d3z-ydnAzsRuO4BUWmV43HRUcWcaagF-Lz55M3lq2
|
||||
parent: null-object; artifact: null-object
|
||||
Puml Server ID: JSV14SCm20J0Lk829Fxf1cF6bWSX3JhYzfDdVhjRSx4yDCDU5p3NcoZugMV3bNik3HaETLGPdPhbm-2WcpzS3btjz38PqF15dTSFv6bMndwhW1Jo_vhHwynkNm00
|
||||
parent: multiton; artifact: multiton
|
||||
Puml Server ID: FST14i8m20NGg-W16lRUXgPCYnD81Zxs-hfozzvJlOywf68yBc3bYoZuRgVYghrIea-7E5gVHZhgPd3Gcp-y7P9w-hOOaF0au_o1h0OKqqdG_saLrbRP-080
|
||||
parent: composite; artifact: composite
|
||||
Puml Server ID: HSf13eCm30NHgy01YFUzZGaM62LEP7-NwvTTT_EaMTLgoqFIst81Cpv4payv5LVk6U9r6CHGwkYaBHy6EztyvUsGqDEsoO2u1NMED-WTvmY5aA3-LT9xcTdR3m00
|
||||
parent: api-gateway; artifact: image-microservice
|
||||
Puml Server ID: 3Sp13SCm2030LTe1RFxTXX3aK1biOOZLxPlVlUujHZrFJk-lAsAk3u3ZhatYoYCNEmqBjgWq5AJdna27BzvOJbxIh4oCOBS5Yki1u9JIC7ZZ3pW8HB5nKI4VJtSBSKtNEbFx7m00
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'api-gateway/etc/image-microservice.urm.puml'
|
||||
pumlid: 3Sp13SCm2030LTe1RFxTXX3aK1biOOZLxPlVlUujHZrFJk-lAsAk3u3ZhatYoYCNEmqBjgWq5AJdna27BzvOJbxIh4oCOBS5Yki1u9JIC7ZZ3pW8HB5nKI4VJtSBSKtNEbFx7m00
|
||||
parent: api-gateway; artifact: api-gateway-service
|
||||
Puml Server ID: JSox3SCm303HLP819FRUXg49cO542_nOyFPncUvUSszHwhbpMdyT4TCt0CDLcyIHdtGsEZLOez8vG7ek33JuueLbPvUcPM84cpeCz2S0fvI6mGjluA1_b-Tt2N5D6tNcw3y0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'api-gateway/etc/api-gateway-service.urm.puml'
|
||||
pumlid: JSox3SCm303HLP819FRUXg49cO542_nOyFPncUvUSszHwhbpMdyT4TCt0CDLcyIHdtGsEZLOez8vG7ek33JuueLbPvUcPM84cpeCz2S0fvI6mGjluA1_b-Tt2N5D6tNcw3y0
|
||||
parent: api-gateway; artifact: price-microservice
|
||||
Puml Server ID: 3Sn13iGW243HgqmFeEpdDfGIoqJK8DJqzkFklyq_f56DYyFgvtOVymjWk78Hl-ECoKQzEJVFr1Mana97Wny-c2wUKbeQwCxM9YZE7O13Ka7dXI-m4mmJugH2rlVksSXXcaTe_GC0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'api-gateway/etc/price-microservice.urm.puml'
|
||||
pumlid: 3Sn13iGW243HgqmFeEpdDfGIoqJK8DJqzkFklyq_f56DYyFgvtOVymjWk78Hl-ECoKQzEJVFr1Mana97Wny-c2wUKbeQwCxM9YZE7O13Ka7dXI-m4mmJugH2rlVksSXXcaTe_GC0
|
||||
parent: object-pool; artifact: object-pool
|
||||
Puml Server ID: JSV94SCm2030Lk829Fxf1cF6bWU1XYDkFtdcjxiD9Qc3o-LrPQvu0pW-_HnvrLx1JgR9cfrimf1wCD7XnW-sWsESsXPcicl0nFW1RB-PiYqp0KxwVo-VVTMKBm00
|
||||
parent: adapter; artifact: adapter
|
||||
Puml Server ID: DSR14S8m30J0Lg20M7-wEMnDOiPMFDA9j0yyUEtUkzMHJTF7xI1NF4GSLzaxZtncgDVJgCPIpobzv0N2vOKtjgRHTziMI7KBcOXl10thfxB-Nz9dMJd71m00
|
||||
parent: hexagonal; artifact: hexagonal
|
||||
Puml Server ID: HSTB4W8X30N0g-W1XkozpPD90LO8L3wEnzUTk-xxq2fvSfhSUiJs1v7XAcr4psSwMrqQh57gcZGaBmICNdZZEDb7qsCZWasT9lm7wln1MmeXZlfVIPjbvvGl
|
||||
parent: value-object; artifact: value-object
|
||||
Puml Server ID: LSZ13SCm20NGLTe1RExTXX2KECBOmfza_VRQszDxDnVBNJFiTG9pVOY2dteqdBdbqf3XK4ULqQbPFWmEklZcikjgXvV9W8Olwhn-e9ijjOpjKW4fv2zgHgypktq1
|
||||
parent: twin; artifact: twin
|
||||
Puml Server ID: 7SR13OCm30NGLUW0n7UsCS42eyH4zdUpFbNVwNtKQij3qjjo0ICs8kTPJiMLUuPuVGnYAFNff2qdWvrk_l9wIEXfws10t88wno-4gKQ2-az9xsLaRoy0
|
||||
parent: semaphore; artifact: semaphore
|
||||
Puml Server ID: HSV14SCm20J0Lk82BFxf1ikCfOn06ZZizfDVVhjRjphobFJnQi2ADv7pKwwEbaU6U9q6CPGwbVh8Xy5E7xvvFoNwPVjYGDo2bEC72b5URRgGeFvNqhMirF45
|
||||
parent: message-channel; artifact: message-channel
|
||||
Puml Server ID: NSZB3SCm203GLTe1RExTXX1akm9YyMdMRy-zFRtdCf8wkLmUCtF72y3nxcFbhAE2dIvBjknqAIof6nCTtlZ1TdAiOMrZ9hi5ACOFe1o1WnjDD6C1Jlg_NgvzbyeN
|
||||
parent: poison-pill; artifact: poison-pill
|
||||
Puml Server ID: JSZ14SCm20NHLf82BExfXiYCJGOX3NpYzkDZRllsgTwjTgcmnmciV145N-rGdFMkbEZJ8OxMvo2rkXWSzE4lRxka7huj1YGyQN3UGMjgpdkh6Gdwlrl5QAk6_G00
|
||||
parent: aggregator-microservices; artifact: aggregator-service
|
||||
Puml Server ID: JOov3SCm301NIGQGs7iRXYPa1g8ayB7NjuiKwGvtmBrbKC-Tq_hhY5Y-0HXUjKaS-Kbdepc2HrIQ2jBpma23BvvOTdPfeooCO1iEYlu0O6l63MDQKI6Rp-CKOWSE-ey_NzEqhjH-0m00
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'aggregator-microservices/etc/aggregator-service.urm.puml'
|
||||
pumlid: JOov3SCm301NIGQGs7iRXYPa1g8ayB7NjuiKwGvtmBrbKC-Tq_hhY5Y-0HXUjKaS-Kbdepc2HrIQ2jBpma23BvvOTdPfeooCO1iEYlu0O6l63MDQKI6Rp-CKOWSE-ey_NzEqhjH-0m00
|
||||
parent: aggregator-microservices; artifact: information-microservice
|
||||
Puml Server ID: LSnB3i8m303Hgy016k-vZN5DQXGxaJ_jzUcMtKXFcgSOZTgvV3oEp1Kl0CUhTScZtXNiD2tPij5Ka54N9ZfyySHjvv1ksy9CTWjGZ3i0UtVkcDCt5V9vFquX3k0a4FjCLqoPzgUjNDig7Jy0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'aggregator-microservices/etc/information-microservice.urm.puml'
|
||||
pumlid: LSnB3i8m303Hgy016k-vZN5DQXGxaJ_jzUcMtKXFcgSOZTgvV3oEp1Kl0CUhTScZtXNiD2tPij5Ka54N9ZfyySHjvv1ksy9CTWjGZ3i0UtVkcDCt5V9vFquX3k0a4FjCLqoPzgUjNDig7Jy0
|
||||
parent: aggregator-microservices; artifact: inventory-microservice
|
||||
Puml Server ID: LSpB3G8n303HLg20ZUzqOxnMrYXn8d-oedjovJRIIEyfIYrFJckFAsBw2y3mBbNYodSw6mqDrYWqEaZB6mCDFhZmEDcbwZ4nWaqTEleEm5gDAyQmemlPsCOIOWSE0j6riM7VlrVIUfdPsmy0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'aggregator-microservices/etc/inventory-microservice.urm.puml'
|
||||
pumlid: LSpB3G8n303HLg20ZUzqOxnMrYXn8d-oedjovJRIIEyfIYrFJckFAsBw2y3mBbNYodSw6mqDrYWqEaZB6mCDFhZmEDcbwZ4nWaqTEleEm5gDAyQmemlPsCOIOWSE0j6riM7VlrVIUfdPsmy0
|
||||
parent: bridge; artifact: bridge
|
||||
Puml Server ID: BSR14SCm20J0Lf82BFxf1akCJ4R26ZZYzkE7zxLljJgoIVfu7S2A3v7pLRhYo3r3l9u6CPHwJjAH5uETllpZhKbejsqn86v1a-CExQwj2mdgqv8-oyev_W00
|
||||
parent: servant; artifact: servant
|
||||
Puml Server ID: DSkn4O0m20NGLNG0G-ys63cDbv0SV7HzRUnUy-QYkSOkONKwWU4haV6JZe8pjd2nt1MYIBatAZKU1XjTVFEoYvT3by60c3erzW_qdPiL9CY_KrXB8rfz0G00
|
||||
parent: lazy-loading; artifact: lazy-loading
|
||||
Puml Server ID: LSXB3W8X303Gg-W1e7jlqu66gIc5zED4JwzRTo_lpjeaEwN9xOpO_W0mlEhWEFD89sjBWpHgMnDOyi90WoU-i7Ho7besHf2fmqJ_0GG_xo8BE-i0YlONDMtMdLE-
|
||||
parent: flyweight; artifact: flyweight
|
||||
Puml Server ID: HSV94S8m3030Lg20M7-w4OvYAoCh7Xtnq3ty-Eq-MQlaJcdow17JNm26gpIEdkzqidffa4Qfrm2MN1XeSEADsqxEJRU94MJgCD1_W4C-YxZr08hwNqaRPUQGBm00
|
||||
parent: mutex; artifact: mutex
|
||||
Puml Server ID: 9SR13OCm30NGLSe0n7UsCS62LB69x6zWV2hrdTxKhFRS9Br_3c34GkHybxtXo3L3l9u6CPHwAhMUDuETldpnl4cqtUR1WBW5ASSlf0bvI53_A-bQHcf_0G00
|
||||
parent: mediator; artifact: mediator
|
||||
Puml Server ID: FSV14SCm20J0Lk82BFxf1akCJKOW3JhizfDNVhkRUktP9AE_Bc2kDr7mKqx5bKSkYJeSuYXr66dFXy517xvvRxBqz7qo8E6BZDSFPDAKCO84zP-IOMMczIy0
|
||||
parent: page-object; artifact: page-object
|
||||
Puml Server ID: JSV14OGW30NGLjO28FVj9iOCua1Wme-sxnxtzjvMJLeS6ju-9p3NbyZvoQNYZ3sMkWo36hACJhN5ms2dYszEXwvQB4q6r6rHv_K3JIwQndwfW1Jo_npUyupUNW00
|
||||
parent: factory-kit; artifact: factory-kit
|
||||
Puml Server ID: JST15i8m20N0g-W14lRU1YcsQ4BooCS-RwzBTpDNSscvQKQx7C1SDwBWi-w68--vD6Gur55bTBAM9uE3dlpcikcotSjaGCCNTLu_q8C58pxbPI25_Bzcz3gpjoy0
|
||||
parent: property; artifact: property
|
||||
Puml Server ID: FSV13OCm30NGLTe1YEziumOBKYMEPN-3s9wUUdlltRJst2Izlmx0OYLolihUSEGdGxnEXIXAdODQpul1Jby-UTaasgwBCI2kGOFZ1pAV9ewR1FMVaZwAvUWF
|
||||
parent: dependency-injection; artifact: dependency-injection
|
||||
Puml Server ID: RSdB3SCW303GLPe1mFTkunWhSGG6-PEesxS3zFQajubIpyPf_NL6B7y363xra3XpJsUZgS4QbUO0wVbWeC65DvR6BeUMXH5iwZ3GVu36YxMnqgU8NamXKu63_aPD6tNbw5y0
|
||||
parent: layers; artifact: layers
|
||||
Puml Server ID: BSR13OCm30NGLSe0n7UsCS62L8w9x6yGszD3t-bDpQhc9kdwEO0H2v7pNVQ68zSCyNeQn53gsQbftWns-lB5yoRHTfi70-8Mr3b-8UL7F4XG_otflOpi-W80
|
||||
parent: producer-consumer; artifact: producer-consumer
|
||||
Puml Server ID: PSjB3iCW303HgxG70Ezx6zTO2HKso9_a-c7VtUX9y-vA8nkdZTSPiVm3O7ZNeyUPttGscXgiKMaAz94t1XhyyCBIsFkXPM44cpe8-WvODbiIMzcdfspXe7-jQL9NodW0
|
||||
parent: builder; artifact: builder
|
||||
Puml Server ID: DSR94O0m2030LhG0mzzkC64KXs26GzlNZw_TcRLADagJwOWOlW8OFcNdE79B9wkN1ccKUdLWoGS33KwySMdalEioC89C7Jhw5zYIfNrIrFybhPUHNLu0
|
||||
parent: specification; artifact: specification
|
||||
Puml Server ID: LSX14i8m20NGg-W16lRU1YcsE0d9mCTUNxVkthoxkVJQjQBVJc3bWoZuQeVXh6UbXao7EfhCGTRhOd3Gcp-yxPfs-BOOqF2amVa3vLAnbmd3ffD2_gTLZBPgz2y0
|
||||
parent: state; artifact: state
|
||||
Puml Server ID: 9SRH3O0m20N0LNG0ox_RO2LQqz867hg-9jxNpKLpZLt2wdG2mrSYuoST1MTiuMAvAqIHSczKQZmCDhhuvcKNBuSkWm4nTMhiNyZ141BaVocifH6jlW00
|
||||
parent: reader-writer-lock; artifact: reader-writer-lock
|
||||
Puml Server ID: RSZB4S8m303HLg00MtUw4R8cCP5bZpwuVL80jttxx4gIZTFaSKOiVm4OxdhqEFETpaPJWpKgpG5TScEWmGU_M1fxFxGiZ61JXu5-1nXZOolR-gqYaoxWe3-xfeswSiWF
|
||||
parent: interpreter; artifact: interpreter
|
||||
Puml Server ID: JSf13eCm30NHgz034E-vZGaM62Kcih_BzQ6xxjv8yr6hBJT9RzC1Z5Y8dE-oAuvSCyJhPH13gLSdRNapsEdaBy-RXEus3mR4BQXpl21zVnykFmlgVvVqNaRszW00
|
||||
parent: template-method; artifact: template-method
|
||||
Puml Server ID: NSZ13SCW30NGLPe1mFTkuu0Lg6n0vZjPlpttzlIEFef6bN1zDM3jDv7paw-E5cTiyJ87P22NQTGr7WOxVVZcL6NtQwJ5WFZOPBn_88WjPKWoGPkL1EN_ShZb5QPV
|
||||
parent: feature-toggle; artifact: feature-toggle
|
||||
Puml Server ID: NSZ14G8X30NGLhG0oDrk8XjPd12OvCTjNy_UthpxiAPvIBhUJc37WyZvgdtWp6U6U5i6CTIs9WtDYy5ER_vmEIH6jx8P4BUWoV43lOIHBWMhTnKIjB-gwRFkdFe5
|
||||
parent: business-delegate; artifact: business-delegate
|
||||
Puml Server ID: POl13SCm3CHMQGU8zUysgYCuBcJ5a4x9-l6_Fu84tzsgvYxf-Zg06HyYvxkqZYE_6UBrD8YXr7DGrxmPxFJZYxTTeZVR9WFY5ZGu5j2wkad4wYgD8IIe_xQaZp9pw0C0
|
||||
parent: naked-objects; artifact: naked-objects-integtests
|
||||
Puml Server ID: LSmn4iCW30NHgoG70FMvZGmQ6ni48tt5ru_RT3kls7VJqgDAM7yTmF8FaV6TzuOZjd2nCXMYo6KEQZrk1XkT_ELKnTkkQJ4Wfaw3_GbIlgIckPrIu2Ge_vBQyziX3izX8wyO_GS0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'naked-objects/etc/naked-objects-integtests.urm.puml'
|
||||
pumlid: LSmn4iCW30NHgoG70FMvZGmQ6ni48tt5ru_RT3kls7VJqgDAM7yTmF8FaV6TzuOZjd2nCXMYo6KEQZrk1XkT_ELKnTkkQJ4Wfaw3_GbIlgIckPrIu2Ge_vBQyziX3izX8wyO_GS0
|
||||
parent: naked-objects; artifact: naked-objects-dom
|
||||
Puml Server ID: LSZ94SCW3030Lf82G7zt8mkDZOC4eyDkF_dcjxFlhZIoSTfudH7BDm33fnuzpjpJsMXgi4QbAT17FXXeSE6DfR7tGyl223Pr4FGVGF73hSpzOWe73lgVqgRKDAahPNm1
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'naked-objects/etc/naked-objects-dom.urm.puml'
|
||||
pumlid: LSZ94SCW3030Lf82G7zt8mkDZOC4eyDkF_dcjxFlhZIoSTfudH7BDm33fnuzpjpJsMXgi4QbAT17FXXeSE6DfR7tGyl223Pr4FGVGF73hSpzOWe73lgVqgRKDAahPNm1
|
||||
parent: naked-objects; artifact: naked-objects-fixture
|
||||
Puml Server ID: LSX15i8W30N0g-W187jlaq9igH1uoO_r-BfrDs_kJKkFAc7zTW3B7qJ6LzuRZjZ2nSfKY2ANEQZrk1XiTFARKnLlkwR5W9Ww3VOVIFabDStjb08dGVcVz6mVX4aE6td5w5y0
|
||||
I dont want to program this, just add the following lines to the README.md file that corresponds to this puml file 'naked-objects/etc/naked-objects-fixture.urm.puml'
|
||||
pumlid: LSX15i8W30N0g-W187jlaq9igH1uoO_r-BfrDs_kJKkFAc7zTW3B7qJ6LzuRZjZ2nSfKY2ANEQZrk1XiTFARKnLlkwR5W9Ww3VOVIFabDStjb08dGVcVz6mVX4aE6td5w5y0
|
||||
parent: model-view-controller; artifact: model-view-controller
|
||||
Puml Server ID: ROl13SCm201NQGUm-NSRQgE42h258Lw_wR-_qvtkoTOaEwNBuuoOwmNWkEl1SUOx5taR5cHHsr1WoOs13X-yi7HQV5YP645k2nJN3Q2ZavIBQPVVwqFajXJjVwdfMcUgV040
|
||||
parent: proxy; artifact: proxy
|
||||
Puml Server ID: 9SR13OCm30NGLM00udktCS62eCI9x6yesrEfx_Jcehd69c5rEe3X7oBZE-q5HwpXOhahH95oRrHgt0msEldYPHClkow30J5rQko_qB3-VKYG_qjXBOrezGK0
|
||||
parent: memento; artifact: memento
|
||||
Puml Server ID: DSgn4OCm30NGLM00h3xR2AC3SvRiaxx2-g59zugtDgiz3qdlomNC-10vF-Lik7BF4A_388PIXrBh-J3OwUOlRuT4EssR38XRa7Ay81Lz_o11_RkaQvcf_GS0
|
||||
parent: decorator; artifact: decorator
|
||||
Puml Server ID: HSV14SCm20J0Lk82BFxf1YF6LaP26ZZizfDVVhjRC-bPDRs_Bc35cyZvAMV3bKU6kao36ehCGQtdms2d3z-yLursshuOKBUWmV43LPNfZEcaaFzA-YWhH_y2
|
||||
parent: data-mapper; artifact: data-mapper
|
||||
Puml Server ID: JShB3OGm303HLg20nFVjnYGM1CN6ycTfVtFSsnjfzY5jPgUqkLqHwXy0mxUU8wuyqidQ8q4IjJqCO-QBWGOtVh5qyd5AKOmW4mT6Nu2-ZiAekapH_hkcSTNa-GC0
|
||||
parent: caching; artifact: caching
|
||||
Puml Server ID: DSRB4OKm2030LhG0m_rrWyWaE0bc-6ZxpujxsbMKUXwSrfSMCVq7OFYKAj5oJsUZIuCr2bq3fEU3WGOdthWTx59rcnZ1fWu3_GqGKXEjm47VIzeeCqV_0m00
|
||||
parent: reactor; artifact: reactor
|
||||
Puml Server ID: DSR14OGm20NGLjO23FVj1f7Hx2Ga0nzjVxtuJc-f9YrtJM-V4vZn9NA-or5nvfQXBiEWXYAZKsrvCzZfnnUlkqOzR9qCg5jGvtX2hYmOJWfvNz9xcTdR7m00
|
||||
parent: iterator; artifact: iterator
|
||||
Puml Server ID: FSV13OGm30NHLg00uljsOu85HeaJsTzB-yjfBwCtgrfjUKXwMovWneV8-IcduiezGxmEWnXA7PsqvSDWfvk_l1qIUjes6H2teCxnWlGDOpW9wdzAUYypU_i1
|
||||
parent: callback; artifact: callback
|
||||
Puml Server ID: FSVB4S8m30N0Lg20M7UwUL4qYOciUFGXxSE9s-wp6sjjKgwF8tF6YyXnjxtdKMk5E5-MOjdu6jIrRYIStlXWsIJwRij4fhW53SGFn51TmIT9yZ-jVBHPGxy0
|
||||
parent: repository; artifact: repository
|
||||
Puml Server ID: JSV13OCm30NGLM00udktCS42eyI9xE-YRjyUUtjlLQij3qblomNCU14vF-LKNBbdYDTX44EfevEsV1ZiTFERjqD2Jzic0-8Mr3b-89SvGZ7yGuBwrvBUoypUlW00
|
||||
parent: mute-idiom; artifact: mute-idiom
|
||||
Puml Server ID: JSf13iCm20NHgxG7iDdtDjH62PKX5luarq-MtSsJvgtUHdR96AyTcEj357pLJR7dDvT4EnpYgEqmqf4NWuD-V7BfidJpCXcGy4N6wmcoX1Jj-lo2ziUQONMcZHi0
|
||||
parent: prototype; artifact: prototype
|
||||
Puml Server ID: HSV13OCm30NGLM00udktCS62eCInxE-YRj_UUdjlRLfx7fBUbmkmU14vF-Lik7BF4AzJ8OfIvw3Mys6mqyrltWw9Tkfc38XhqE3uWSmd9Zuc9AZ_bVHHB4V_0W00
|
||||
parent: step-builder; artifact: step-builder
|
||||
Puml Server ID: LOZ93SCm3C1MQGQmzUysYYqaAcJ5q96i7t_x8KXkh4soKvfypeZfNm33fnuSP-xfPEtI88tQhW4i-M2WmGzlB9sS3oqJ8yZKOQ0lWOLPzcJfAoZQtwXfeyuSyW80
|
||||
parent: double-checked-locking; artifact: double-checked-locking
|
||||
Puml Server ID: TSdH4SCW203GLTe1bFzkGv1J6qGFeLc_MI1_x-wzkv94uJ1vDVUrFm26LwxTMnonsMYgitgcEQ1BNEXeyCKVfiAxLqqBtTbqmy1z0ygCGpXHOpgv99bqTgt0JW-LmqPUCUGF
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>abstract-document</artifactId>
|
||||
<dependencies>
|
||||
|
@ -18,7 +18,107 @@ Kit
|
||||
Provide an interface for creating families of related or dependent
|
||||
objects without specifying their concrete classes.
|
||||
|
||||

|
||||
## Explanation
|
||||
Real world example
|
||||
|
||||
> To create a kingdom we need objects with common theme. Elven kingdom needs an Elven king, Elven castle and Elven army whereas Orcish kingdom needs an Orcish king, Orcish castle and Orcish army. There is a dependency between the objects in the kingdom.
|
||||
|
||||
In plain words
|
||||
|
||||
> A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
Translating the kingdom example above. First of all we have some interfaces and implementation for the objects in the kingdom
|
||||
|
||||
```
|
||||
public interface Castle {
|
||||
String getDescription();
|
||||
}
|
||||
public interface King {
|
||||
String getDescription();
|
||||
}
|
||||
public interface Army {
|
||||
String getDescription();
|
||||
}
|
||||
|
||||
// Elven implementations ->
|
||||
public class ElfCastle implements Castle {
|
||||
static final String DESCRIPTION = "This is the Elven castle!";
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return DESCRIPTION;
|
||||
}
|
||||
}
|
||||
public class ElfKing implements King {
|
||||
static final String DESCRIPTION = "This is the Elven king!";
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return DESCRIPTION;
|
||||
}
|
||||
}
|
||||
public class ElfArmy implements Army {
|
||||
static final String DESCRIPTION = "This is the Elven Army!";
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return DESCRIPTION;
|
||||
}
|
||||
}
|
||||
|
||||
// Orcish implementations similarly...
|
||||
|
||||
```
|
||||
|
||||
Then we have the abstraction and implementations for the kingdom factory
|
||||
|
||||
```
|
||||
public interface KingdomFactory {
|
||||
Castle createCastle();
|
||||
King createKing();
|
||||
Army createArmy();
|
||||
}
|
||||
|
||||
public class ElfKingdomFactory implements KingdomFactory {
|
||||
public Castle createCastle() {
|
||||
return new ElfCastle();
|
||||
}
|
||||
public King createKing() {
|
||||
return new ElfKing();
|
||||
}
|
||||
public Army createArmy() {
|
||||
return new ElfArmy();
|
||||
}
|
||||
}
|
||||
|
||||
public class OrcKingdomFactory implements KingdomFactory {
|
||||
public Castle createCastle() {
|
||||
return new OrcCastle();
|
||||
}
|
||||
public King createKing() {
|
||||
return new OrcKing();
|
||||
}
|
||||
public Army createArmy() {
|
||||
return new OrcArmy();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now we have our abstract factory that lets us make family of related objects i.e. Elven kingdom factory creates Elven castle, king and army etc.
|
||||
|
||||
```
|
||||
KingdomFactory factory = new ElfKingdomFactory();
|
||||
Castle castle = factory.createCastle();
|
||||
King king = factory.createKing();
|
||||
Army army = factory.createArmy();
|
||||
|
||||
castle.getDescription(); // Output: This is the Elven castle!
|
||||
king.getDescription(); // Output: This is the Elven king!
|
||||
army.getDescription(); // Output: This is the Elven Army!
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use the Abstract Factory pattern when
|
||||
@ -41,9 +141,6 @@ Use the Abstract Factory pattern when
|
||||
|
||||
* Dependency injection in java hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
|
||||
|
||||
|
||||
|
||||
|
||||
## Real world examples
|
||||
|
||||
* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
|
||||
|
Before Width: | Height: | Size: 21 KiB |
@ -1,159 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
||||
<interface id="1" language="java" name="com.iluwatar.abstractfactory.Army" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Army.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="70" width="161" x="1407" y="300"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<interface id="2" language="java" name="com.iluwatar.abstractfactory.KingdomFactory" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/KingdomFactory.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="161" x="1001" y="300"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<class id="3" language="java" name="com.iluwatar.abstractfactory.ElfCastle" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfCastle.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="96" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="4" language="java" name="com.iluwatar.abstractfactory.ElfKingdomFactory" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKingdomFactory.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="142" width="161" x="900" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="5" language="java" name="com.iluwatar.abstractfactory.ElfKing" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfKing.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="498" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<interface id="6" language="java" name="com.iluwatar.abstractfactory.King" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/King.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="70" width="161" x="599" y="300"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<class id="7" language="java" name="com.iluwatar.abstractfactory.OrcCastle" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcCastle.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="297" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="8" language="java" name="com.iluwatar.abstractfactory.OrcKing" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKing.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="699" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="9" language="java" name="com.iluwatar.abstractfactory.ElfArmy" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/ElfArmy.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="1306" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="10" language="java" name="com.iluwatar.abstractfactory.OrcArmy" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcArmy.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="106" width="161" x="1507" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<interface id="11" language="java" name="com.iluwatar.abstractfactory.Castle" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/Castle.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="70" width="161" x="197" y="300"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<class id="12" language="java" name="com.iluwatar.abstractfactory.OrcKingdomFactory" project="abstract-factory"
|
||||
file="/abstract-factory/src/main/java/com/iluwatar/abstractfactory/OrcKingdomFactory.java" binary="false"
|
||||
corner="BOTTOM_RIGHT">
|
||||
<position height="142" width="165" x="1101" y="118"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<realization id="13">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</realization>
|
||||
<realization id="14">
|
||||
<end type="SOURCE" refId="7"/>
|
||||
<end type="TARGET" refId="11"/>
|
||||
</realization>
|
||||
<realization id="15">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="6"/>
|
||||
</realization>
|
||||
<realization id="16">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="11"/>
|
||||
</realization>
|
||||
<realization id="17">
|
||||
<end type="SOURCE" refId="10"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<realization id="18">
|
||||
<end type="SOURCE" refId="12"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</realization>
|
||||
<realization id="19">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="6"/>
|
||||
</realization>
|
||||
<realization id="20">
|
||||
<end type="SOURCE" refId="9"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
@ -1,89 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.abstractfactory {
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
- army : Army
|
||||
- castle : Castle
|
||||
- king : King
|
||||
+ App()
|
||||
+ createKingdom(factory : KingdomFactory)
|
||||
+ getArmy() : Army
|
||||
~ getArmy(factory : KingdomFactory) : Army
|
||||
+ getCastle() : Castle
|
||||
~ getCastle(factory : KingdomFactory) : Castle
|
||||
+ getKing() : King
|
||||
~ getKing(factory : KingdomFactory) : King
|
||||
+ main(args : String[]) {static}
|
||||
- setArmy(army : Army)
|
||||
- setCastle(castle : Castle)
|
||||
- setKing(king : King)
|
||||
}
|
||||
interface Army {
|
||||
+ getDescription() : String {abstract}
|
||||
}
|
||||
interface Castle {
|
||||
+ getDescription() : String {abstract}
|
||||
}
|
||||
class ElfArmy {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ ElfArmy()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class ElfCastle {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ ElfCastle()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class ElfKing {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ ElfKing()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class ElfKingdomFactory {
|
||||
+ ElfKingdomFactory()
|
||||
+ createArmy() : Army
|
||||
+ createCastle() : Castle
|
||||
+ createKing() : King
|
||||
}
|
||||
interface King {
|
||||
+ getDescription() : String {abstract}
|
||||
}
|
||||
interface KingdomFactory {
|
||||
+ createArmy() : Army {abstract}
|
||||
+ createCastle() : Castle {abstract}
|
||||
+ createKing() : King {abstract}
|
||||
}
|
||||
class OrcArmy {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ OrcArmy()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class OrcCastle {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ OrcCastle()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class OrcKing {
|
||||
~ DESCRIPTION : String {static}
|
||||
+ OrcKing()
|
||||
+ getDescription() : String
|
||||
}
|
||||
class OrcKingdomFactory {
|
||||
+ OrcKingdomFactory()
|
||||
+ createArmy() : Army
|
||||
+ createCastle() : Castle
|
||||
+ createKing() : King
|
||||
}
|
||||
}
|
||||
App --> "-castle" Castle
|
||||
App --> "-king" King
|
||||
App --> "-army" Army
|
||||
ElfArmy ..|> Army
|
||||
ElfCastle ..|> Castle
|
||||
ElfKing ..|> King
|
||||
ElfKingdomFactory ..|> KingdomFactory
|
||||
OrcArmy ..|> Army
|
||||
OrcCastle ..|> Castle
|
||||
OrcKing ..|> King
|
||||
OrcKingdomFactory ..|> KingdomFactory
|
||||
@enduml
|
Before Width: | Height: | Size: 57 KiB |
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>abstract-factory</artifactId>
|
||||
<dependencies>
|
||||
|
@ -19,10 +19,85 @@ Convert the interface of a class into another interface the clients
|
||||
expect. Adapter lets classes work together that couldn't otherwise because of
|
||||
incompatible interfaces.
|
||||
|
||||

|
||||
## Explanation
|
||||
|
||||
## General usage of Adapter Pattern:
|
||||
+ Wrappers used to adopt 3rd parties libraries and frameworks - most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
|
||||
Real world example
|
||||
|
||||
> Consider that you have some pictures in your memory card and you need to transfer them to your computer. In order to transfer them you need some kind of adapter that is compatible with your computer ports so that you can attach memory card to your computer. In this case card reader is an adapter.
|
||||
> Another example would be the famous power adapter; a three legged plug can't be connected to a two pronged outlet, it needs to use a power adapter that makes it compatible with the two pronged outlet.
|
||||
> Yet another example would be a translator translating words spoken by one person to another
|
||||
|
||||
In plain words
|
||||
|
||||
> Adapter pattern lets you wrap an otherwise incompatible object in an adapter to make it compatible with another class.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used as another interface. It is often used to make existing classes work with others without modifying their source code.
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
Consider a captain that can only use rowing boats and cannot sail at all.
|
||||
|
||||
First we have interfaces `RowingBoat` and `FishingBoat`
|
||||
|
||||
```
|
||||
public interface RowingBoat {
|
||||
void row();
|
||||
}
|
||||
|
||||
public class FishingBoat {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class);
|
||||
public void sail() {
|
||||
LOGGER.info("The fishing boat is sailing");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And captain expects an implementation of `RowingBoat` interface to be able to move
|
||||
|
||||
```
|
||||
public class Captain implements RowingBoat {
|
||||
|
||||
private RowingBoat rowingBoat;
|
||||
|
||||
public Captain(RowingBoat rowingBoat) {
|
||||
this.rowingBoat = rowingBoat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void row() {
|
||||
rowingBoat.row();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now let's say the pirates are coming and our captain needs to escape but there is only fishing boat available. We need to create an adapter that allows the captain to operate the fishing boat with his rowing boat skills.
|
||||
|
||||
```
|
||||
public class FishingBoatAdapter implements RowingBoat {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoatAdapter.class);
|
||||
|
||||
private FishingBoat boat;
|
||||
|
||||
public FishingBoatAdapter() {
|
||||
boat = new FishingBoat();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void row() {
|
||||
boat.sail();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And now the `Captain` can use the `FishingBoat` to escape the pirates.
|
||||
|
||||
```
|
||||
Captain captain = new Captain(new FishingBoatAdapter());
|
||||
captain.row();
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use the Adapter pattern when
|
||||
@ -30,6 +105,7 @@ Use the Adapter pattern when
|
||||
* you want to use an existing class, and its interface does not match the one you need
|
||||
* you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces
|
||||
* you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.
|
||||
* most of the applications using third party libraries use adapters as a middle layer between the application and the 3rd party library to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.
|
||||
|
||||
## Consequences:
|
||||
Class and object adapters have different trade-offs. A class adapter
|
||||
|
Before Width: | Height: | Size: 12 KiB |
@ -1,37 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.adapter {
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class BattleFishingBoat {
|
||||
- LOGGER : Logger {static}
|
||||
- boat : FishingBoat
|
||||
+ BattleFishingBoat()
|
||||
+ fire()
|
||||
+ move()
|
||||
}
|
||||
interface BattleShip {
|
||||
+ fire() {abstract}
|
||||
+ move() {abstract}
|
||||
}
|
||||
class Captain {
|
||||
- battleship : BattleShip
|
||||
+ Captain()
|
||||
+ Captain(battleship : BattleShip)
|
||||
+ fire()
|
||||
+ move()
|
||||
+ setBattleship(battleship : BattleShip)
|
||||
}
|
||||
class FishingBoat {
|
||||
- LOGGER : Logger {static}
|
||||
+ FishingBoat()
|
||||
+ fish()
|
||||
+ sail()
|
||||
}
|
||||
}
|
||||
BattleFishingBoat --> "-boat" FishingBoat
|
||||
Captain --> "-battleship" BattleShip
|
||||
BattleFishingBoat ..|> BattleShip
|
||||
Captain ..|> BattleShip
|
||||
@enduml
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>adapter</artifactId>
|
||||
<dependencies>
|
||||
|
@ -34,14 +34,14 @@ package com.iluwatar.adapter;
|
||||
* object. This example uses the object adapter approach.
|
||||
*
|
||||
* <p>
|
||||
* The Adapter ({@link BattleFishingBoat}) converts the interface of the adaptee class (
|
||||
* {@link FishingBoat}) into a suitable one expected by the client ( {@link BattleShip} ).
|
||||
* The Adapter ({@link FishingBoatAdapter}) converts the interface of the adaptee class (
|
||||
* {@link FishingBoat}) into a suitable one expected by the client ( {@link RowingBoat} ).
|
||||
*
|
||||
* <p>
|
||||
* The story of this implementation is this. <br>
|
||||
* Pirates are coming! we need a {@link BattleShip} to fight! We have a {@link FishingBoat} and our
|
||||
* Pirates are coming! we need a {@link RowingBoat} to flee! We have a {@link FishingBoat} and our
|
||||
* captain. We have no time to make up a new ship! we need to reuse this {@link FishingBoat}. The
|
||||
* captain needs a battleship which can fire and move. The spec is in {@link BattleShip}. We will
|
||||
* captain needs a rowing boat which he can operate. The spec is in {@link RowingBoat}. We will
|
||||
* use the Adapter pattern to reuse {@link FishingBoat}.
|
||||
*
|
||||
*/
|
||||
@ -53,8 +53,8 @@ public class App {
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Captain captain = new Captain(new BattleFishingBoat());
|
||||
captain.move();
|
||||
captain.fire();
|
||||
// The captain can only operate rowing boats but with adapter he is able to use fishing boats as well
|
||||
Captain captain = new Captain(new FishingBoatAdapter());
|
||||
captain.row();
|
||||
}
|
||||
}
|
||||
|
@ -23,33 +23,26 @@
|
||||
package com.iluwatar.adapter;
|
||||
|
||||
/**
|
||||
* The Captain uses {@link BattleShip} to fight. <br>
|
||||
* The Captain uses {@link RowingBoat} to sail. <br>
|
||||
* This is the client in the pattern.
|
||||
*/
|
||||
public class Captain implements BattleShip {
|
||||
public class Captain implements RowingBoat {
|
||||
|
||||
private BattleShip battleship;
|
||||
private RowingBoat rowingBoat;
|
||||
|
||||
public Captain() {
|
||||
public Captain() {}
|
||||
|
||||
public Captain(RowingBoat rowingBoat) {
|
||||
this.rowingBoat = rowingBoat;
|
||||
}
|
||||
|
||||
public Captain(BattleShip battleship) {
|
||||
this.battleship = battleship;
|
||||
}
|
||||
|
||||
public void setBattleship(BattleShip battleship) {
|
||||
this.battleship = battleship;
|
||||
public void setRowingBoat(RowingBoat rowingBoat) {
|
||||
this.rowingBoat = rowingBoat;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fire() {
|
||||
battleship.fire();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move() {
|
||||
battleship.move();
|
||||
public void row() {
|
||||
rowingBoat.row();
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -27,7 +27,8 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Device class (adaptee in the pattern). We want to reuse this class
|
||||
* Device class (adaptee in the pattern). We want to reuse this class.
|
||||
* Fishing boat moves by sailing.
|
||||
*
|
||||
*/
|
||||
public class FishingBoat {
|
||||
@ -35,11 +36,7 @@ public class FishingBoat {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FishingBoat.class);
|
||||
|
||||
public void sail() {
|
||||
LOGGER.info("The Boat is moving to that place");
|
||||
}
|
||||
|
||||
public void fish() {
|
||||
LOGGER.info("fishing ...");
|
||||
LOGGER.info("The fishing boat is sailing");
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -20,28 +20,24 @@
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
package com.iluwatar.adapter;
|
||||
|
||||
/**
|
||||
*
|
||||
* MagicWeapon
|
||||
*
|
||||
*
|
||||
* Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link RowingBoat}
|
||||
* interface expected by the client ({@link Captain}).
|
||||
*
|
||||
*/
|
||||
public abstract class MagicWeapon {
|
||||
public class FishingBoatAdapter implements RowingBoat {
|
||||
|
||||
protected MagicWeaponImpl imp;
|
||||
private FishingBoat boat;
|
||||
|
||||
public MagicWeapon(MagicWeaponImpl imp) {
|
||||
this.imp = imp;
|
||||
public FishingBoatAdapter() {
|
||||
boat = new FishingBoat();
|
||||
}
|
||||
|
||||
public abstract void wield();
|
||||
|
||||
public abstract void swing();
|
||||
|
||||
public abstract void unwield();
|
||||
|
||||
public MagicWeaponImpl getImp() {
|
||||
return imp;
|
||||
@Override
|
||||
public void row() {
|
||||
boat.sail();
|
||||
}
|
||||
}
|
@ -24,13 +24,11 @@ package com.iluwatar.adapter;
|
||||
|
||||
/**
|
||||
* The interface expected by the client.<br>
|
||||
* A Battleship can fire and move.
|
||||
* A rowing boat is rowed to move.
|
||||
*
|
||||
*/
|
||||
public interface BattleShip {
|
||||
public interface RowingBoat {
|
||||
|
||||
void fire();
|
||||
|
||||
void move();
|
||||
void row();
|
||||
|
||||
}
|
@ -39,9 +39,9 @@ public class AdapterPatternTest {
|
||||
|
||||
private Map<String, Object> beans;
|
||||
|
||||
private static final String BATTLESHIP_BEAN = "engineer";
|
||||
private static final String FISHING_BEAN = "fisher";
|
||||
|
||||
private static final String CAPTAIN_BEAN = "captain";
|
||||
private static final String ROWING_BEAN = "captain";
|
||||
|
||||
/**
|
||||
* This method runs before the test execution and sets the bean objects in the beans Map.
|
||||
@ -50,34 +50,29 @@ public class AdapterPatternTest {
|
||||
public void setup() {
|
||||
beans = new HashMap<>();
|
||||
|
||||
BattleFishingBoat battleFishingBoat = spy(new BattleFishingBoat());
|
||||
beans.put(BATTLESHIP_BEAN, battleFishingBoat);
|
||||
FishingBoatAdapter fishingBoatAdapter = spy(new FishingBoatAdapter());
|
||||
beans.put(FISHING_BEAN, fishingBoatAdapter);
|
||||
|
||||
Captain captain = new Captain();
|
||||
captain.setBattleship((BattleFishingBoat) beans.get(BATTLESHIP_BEAN));
|
||||
beans.put(CAPTAIN_BEAN, captain);
|
||||
captain.setRowingBoat((FishingBoatAdapter) beans.get(FISHING_BEAN));
|
||||
beans.put(ROWING_BEAN, captain);
|
||||
}
|
||||
|
||||
/**
|
||||
* This test asserts that when we use the move() method on a captain bean(client), it is
|
||||
* internally calling move method on the battleship object. The Adapter ({@link BattleFishingBoat}
|
||||
* This test asserts that when we use the row() method on a captain bean(client), it is
|
||||
* internally calling sail method on the fishing boat object. The Adapter ({@link FishingBoatAdapter}
|
||||
* ) converts the interface of the target class ( {@link FishingBoat}) into a suitable one
|
||||
* expected by the client ({@link Captain} ).
|
||||
*/
|
||||
@Test
|
||||
public void testAdapter() {
|
||||
BattleShip captain = (BattleShip) beans.get(CAPTAIN_BEAN);
|
||||
RowingBoat captain = (RowingBoat) beans.get(ROWING_BEAN);
|
||||
|
||||
// when captain moves
|
||||
captain.move();
|
||||
captain.row();
|
||||
|
||||
// the captain internally calls the battleship object to move
|
||||
BattleShip battleship = (BattleShip) beans.get(BATTLESHIP_BEAN);
|
||||
verify(battleship).move();
|
||||
|
||||
// same with above with firing
|
||||
captain.fire();
|
||||
verify(battleship).fire();
|
||||
|
||||
RowingBoat adapter = (RowingBoat) beans.get(FISHING_BEAN);
|
||||
verify(adapter).row();
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>aggregator-microservices</artifactId>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>api-gateway-service</artifactId>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>api-gateway</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>async-method-invocation</artifactId>
|
||||
<dependencies>
|
||||
|
@ -139,7 +139,7 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
|
||||
@Override
|
||||
public void await() throws InterruptedException {
|
||||
synchronized (lock) {
|
||||
if (!isCompleted()) {
|
||||
while (!isCompleted()) {
|
||||
lock.wait();
|
||||
}
|
||||
}
|
||||
|
@ -23,5 +23,5 @@ Use the Balking pattern when
|
||||
but for an unknown amount of time
|
||||
|
||||
## Related patterns
|
||||
* Guarded Suspendion Pattern
|
||||
* Guarded Suspension Pattern
|
||||
* Double Checked Locking Pattern
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
166
bridge/README.md
@ -15,10 +15,170 @@ tags:
|
||||
Handle/Body
|
||||
|
||||
## Intent
|
||||
Decouple an abstraction from its implementation so that the two can
|
||||
vary independently.
|
||||
Decouple an abstraction from its implementation so that the two can vary independently.
|
||||
|
||||

|
||||
## Explanation
|
||||
|
||||
Real world example
|
||||
|
||||
> Consider you have a weapon with different enchantments and you are supposed to allow mixing different weapons with different enchantments. What would you do? Create multiple copies of each of the weapons for each of the enchantments or would you just create separate enchantment and set it for the weapon as needed? Bridge pattern allows you to do the second.
|
||||
|
||||
In Plain Words
|
||||
|
||||
> Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently"
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
Translating our weapon example from above. Here we have the `Weapon` hierarchy
|
||||
|
||||
```
|
||||
public interface Weapon {
|
||||
void wield();
|
||||
void swing();
|
||||
void unwield();
|
||||
Enchantment getEnchantment();
|
||||
}
|
||||
|
||||
public class Sword implements Weapon {
|
||||
|
||||
private final Enchantment enchantment;
|
||||
|
||||
public Sword(Enchantment enchantment) {
|
||||
this.enchantment = enchantment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void wield() {
|
||||
LOGGER.info("The sword is wielded.");
|
||||
enchantment.onActivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
LOGGER.info("The sword is swinged.");
|
||||
enchantment.apply();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwield() {
|
||||
LOGGER.info("The sword is unwielded.");
|
||||
enchantment.onDeactivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enchantment getEnchantment() {
|
||||
return enchantment;
|
||||
}
|
||||
}
|
||||
|
||||
public class Hammer implements Weapon {
|
||||
|
||||
private final Enchantment enchantment;
|
||||
|
||||
public Hammer(Enchantment enchantment) {
|
||||
this.enchantment = enchantment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void wield() {
|
||||
LOGGER.info("The hammer is wielded.");
|
||||
enchantment.onActivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
LOGGER.info("The hammer is swinged.");
|
||||
enchantment.apply();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwield() {
|
||||
LOGGER.info("The hammer is unwielded.");
|
||||
enchantment.onDeactivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enchantment getEnchantment() {
|
||||
return enchantment;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And the separate enchantment hierarchy
|
||||
|
||||
```
|
||||
public interface Enchantment {
|
||||
void onActivate();
|
||||
void apply();
|
||||
void onDeactivate();
|
||||
}
|
||||
|
||||
public class FlyingEnchantment implements Enchantment {
|
||||
|
||||
@Override
|
||||
public void onActivate() {
|
||||
LOGGER.info("The item begins to glow faintly.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply() {
|
||||
LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeactivate() {
|
||||
LOGGER.info("The item's glow fades.");
|
||||
}
|
||||
}
|
||||
|
||||
public class SoulEatingEnchantment implements Enchantment {
|
||||
|
||||
@Override
|
||||
public void onActivate() {
|
||||
LOGGER.info("The item spreads bloodlust.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply() {
|
||||
LOGGER.info("The item eats the soul of enemies.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDeactivate() {
|
||||
LOGGER.info("Bloodlust slowly disappears.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And both the hierarchies in action
|
||||
|
||||
```
|
||||
Sword enchantedSword = new Sword(new SoulEatingEnchantment());
|
||||
enchantedSword.wield();
|
||||
enchantedSword.swing();
|
||||
enchantedSword.unwield();
|
||||
// The sword is wielded.
|
||||
// The item spreads bloodlust.
|
||||
// The sword is swinged.
|
||||
// The item eats the soul of enemies.
|
||||
// The sword is unwielded.
|
||||
// Bloodlust slowly disappears.
|
||||
|
||||
Hammer hammer = new Hammer(new FlyingEnchantment());
|
||||
hammer.wield();
|
||||
hammer.swing();
|
||||
hammer.unwield();
|
||||
// The hammer is wielded.
|
||||
// The item begins to glow faintly.
|
||||
// The hammer is swinged.
|
||||
// The item flies and strikes the enemies finally returning to owner's hand.
|
||||
// The hammer is unwielded.
|
||||
// The item's glow fades.
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use the Bridge pattern when
|
||||
|
Before Width: | Height: | Size: 52 KiB |
@ -1,157 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
||||
<class id="1" language="java" name="com.iluwatar.bridge.FlyingMagicWeaponImpl" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="515" y="591"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="2" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeaponImpl" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="791" y="605"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="3" language="java" name="com.iluwatar.bridge.Stormbringer" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="791" y="788"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="4" language="java" name="com.iluwatar.bridge.MagicWeaponImpl" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="791" y="433"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="5" language="java" name="com.iluwatar.bridge.BlindingMagicWeaponImpl" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1105" y="593"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="6" language="java" name="com.iluwatar.bridge.SoulEatingMagicWeapon" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="380" y="21"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="7" language="java" name="com.iluwatar.bridge.Excalibur" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1105" y="782"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="8" language="java" name="com.iluwatar.bridge.Mjollnir" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="515" y="788"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="9" language="java" name="com.iluwatar.bridge.BlindingMagicWeapon" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="791" y="14"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="10" language="java" name="com.iluwatar.bridge.MagicWeapon" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="791" y="237"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="11" language="java" name="com.iluwatar.bridge.FlyingMagicWeapon" project="bridge"
|
||||
file="/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="1144" y="12"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<generalization id="12">
|
||||
<end type="SOURCE" refId="8"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</generalization>
|
||||
<generalization id="13">
|
||||
<end type="SOURCE" refId="1"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<generalization id="14">
|
||||
<end type="SOURCE" refId="9"/>
|
||||
<end type="TARGET" refId="10"/>
|
||||
</generalization>
|
||||
<generalization id="15">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<association id="16">
|
||||
<end type="SOURCE" refId="10" navigable="false">
|
||||
<attribute id="17" name="imp">
|
||||
<position height="0" width="0" x="478" y="284"/>
|
||||
</attribute>
|
||||
<multiplicity id="18" minimum="0" maximum="1">
|
||||
<position height="0" width="0" x="478" y="284"/>
|
||||
</multiplicity>
|
||||
</end>
|
||||
<end type="TARGET" refId="4" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<generalization id="19">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<generalization id="20">
|
||||
<end type="SOURCE" refId="6"/>
|
||||
<end type="TARGET" refId="10"/>
|
||||
</generalization>
|
||||
<generalization id="21">
|
||||
<end type="SOURCE" refId="7"/>
|
||||
<end type="TARGET" refId="5"/>
|
||||
</generalization>
|
||||
<generalization id="22">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="2"/>
|
||||
</generalization>
|
||||
<generalization id="23">
|
||||
<end type="SOURCE" refId="11"/>
|
||||
<end type="TARGET" refId="10"/>
|
||||
</generalization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
@ -1,92 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.bridge {
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class BlindingMagicWeapon {
|
||||
+ BlindingMagicWeapon(imp : BlindingMagicWeaponImpl)
|
||||
+ blind()
|
||||
+ getImp() : BlindingMagicWeaponImpl
|
||||
+ swing()
|
||||
+ unwield()
|
||||
+ wield()
|
||||
}
|
||||
abstract class BlindingMagicWeaponImpl {
|
||||
+ BlindingMagicWeaponImpl()
|
||||
+ blindImp() {abstract}
|
||||
}
|
||||
class Excalibur {
|
||||
- LOGGER : Logger {static}
|
||||
+ Excalibur()
|
||||
+ blindImp()
|
||||
+ swingImp()
|
||||
+ unwieldImp()
|
||||
+ wieldImp()
|
||||
}
|
||||
class FlyingMagicWeapon {
|
||||
+ FlyingMagicWeapon(imp : FlyingMagicWeaponImpl)
|
||||
+ fly()
|
||||
+ getImp() : FlyingMagicWeaponImpl
|
||||
+ swing()
|
||||
+ unwield()
|
||||
+ wield()
|
||||
}
|
||||
abstract class FlyingMagicWeaponImpl {
|
||||
+ FlyingMagicWeaponImpl()
|
||||
+ flyImp() {abstract}
|
||||
}
|
||||
abstract class MagicWeapon {
|
||||
# imp : MagicWeaponImpl
|
||||
+ MagicWeapon(imp : MagicWeaponImpl)
|
||||
+ getImp() : MagicWeaponImpl
|
||||
+ swing() {abstract}
|
||||
+ unwield() {abstract}
|
||||
+ wield() {abstract}
|
||||
}
|
||||
abstract class MagicWeaponImpl {
|
||||
+ MagicWeaponImpl()
|
||||
+ swingImp() {abstract}
|
||||
+ unwieldImp() {abstract}
|
||||
+ wieldImp() {abstract}
|
||||
}
|
||||
class Mjollnir {
|
||||
- LOGGER : Logger {static}
|
||||
+ Mjollnir()
|
||||
+ flyImp()
|
||||
+ swingImp()
|
||||
+ unwieldImp()
|
||||
+ wieldImp()
|
||||
}
|
||||
class SoulEatingMagicWeapon {
|
||||
+ SoulEatingMagicWeapon(imp : SoulEatingMagicWeaponImpl)
|
||||
+ eatSoul()
|
||||
+ getImp() : SoulEatingMagicWeaponImpl
|
||||
+ swing()
|
||||
+ unwield()
|
||||
+ wield()
|
||||
}
|
||||
abstract class SoulEatingMagicWeaponImpl {
|
||||
+ SoulEatingMagicWeaponImpl()
|
||||
+ eatSoulImp() {abstract}
|
||||
}
|
||||
class Stormbringer {
|
||||
- LOGGER : Logger {static}
|
||||
+ Stormbringer()
|
||||
+ eatSoulImp()
|
||||
+ swingImp()
|
||||
+ unwieldImp()
|
||||
+ wieldImp()
|
||||
}
|
||||
}
|
||||
MagicWeapon --> "-imp" MagicWeaponImpl
|
||||
BlindingMagicWeapon --|> MagicWeapon
|
||||
BlindingMagicWeaponImpl --|> MagicWeaponImpl
|
||||
Excalibur --|> BlindingMagicWeaponImpl
|
||||
FlyingMagicWeapon --|> MagicWeapon
|
||||
FlyingMagicWeaponImpl --|> MagicWeaponImpl
|
||||
Mjollnir --|> FlyingMagicWeaponImpl
|
||||
SoulEatingMagicWeapon --|> MagicWeapon
|
||||
SoulEatingMagicWeaponImpl --|> MagicWeaponImpl
|
||||
Stormbringer --|> SoulEatingMagicWeaponImpl
|
||||
@enduml
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>bridge</artifactId>
|
||||
<dependencies>
|
||||
|
@ -22,40 +22,42 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* The Bridge pattern can also be thought of as two layers of abstraction. With Bridge, you can
|
||||
* decouple an abstraction from its implementation so that the two can vary independently.
|
||||
* Composition over inheritance. The Bridge pattern can also be thought of as two layers of abstraction.
|
||||
* With Bridge, you can decouple an abstraction from its implementation so that the two can vary independently.
|
||||
* <p>
|
||||
* In Bridge pattern both abstraction ({@link MagicWeapon}) and implementation (
|
||||
* {@link MagicWeaponImpl}) have their own class hierarchies. The interface of the implementations
|
||||
* In Bridge pattern both abstraction ({@link Weapon}) and implementation (
|
||||
* {@link Enchantment}) have their own class hierarchies. The interface of the implementations
|
||||
* can be changed without affecting the clients.
|
||||
* <p>
|
||||
* In this example we have two class hierarchies. One of weapons and another one of enchantments. We can easily
|
||||
* combine any weapon with any enchantment using composition instead of creating deep class hierarchy.
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
|
||||
|
||||
/**
|
||||
* Program entry point
|
||||
*
|
||||
* @param args command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(new Excalibur());
|
||||
blindingMagicWeapon.wield();
|
||||
blindingMagicWeapon.blind();
|
||||
blindingMagicWeapon.swing();
|
||||
blindingMagicWeapon.unwield();
|
||||
LOGGER.info("The knight receives an enchanted sword.");
|
||||
Sword enchantedSword = new Sword(new SoulEatingEnchantment());
|
||||
enchantedSword.wield();
|
||||
enchantedSword.swing();
|
||||
enchantedSword.unwield();
|
||||
|
||||
FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(new Mjollnir());
|
||||
flyingMagicWeapon.wield();
|
||||
flyingMagicWeapon.fly();
|
||||
flyingMagicWeapon.swing();
|
||||
flyingMagicWeapon.unwield();
|
||||
|
||||
SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(new Stormbringer());
|
||||
soulEatingMagicWeapon.wield();
|
||||
soulEatingMagicWeapon.swing();
|
||||
soulEatingMagicWeapon.eatSoul();
|
||||
soulEatingMagicWeapon.unwield();
|
||||
LOGGER.info("The valkyrie receives an enchanted hammer.");
|
||||
Hammer hammer = new Hammer(new FlyingEnchantment());
|
||||
hammer.wield();
|
||||
hammer.swing();
|
||||
hammer.unwield();
|
||||
}
|
||||
}
|
||||
|
@ -24,11 +24,14 @@ package com.iluwatar.bridge;
|
||||
|
||||
/**
|
||||
*
|
||||
* FlyingMagicWeaponImpl
|
||||
*
|
||||
* Enchantment
|
||||
*
|
||||
*/
|
||||
public abstract class FlyingMagicWeaponImpl extends MagicWeaponImpl {
|
||||
public interface Enchantment {
|
||||
|
||||
public abstract void flyImp();
|
||||
void onActivate();
|
||||
|
||||
void apply();
|
||||
|
||||
void onDeactivate();
|
||||
}
|
@ -27,30 +27,25 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Excalibur
|
||||
* FlyingEnchantment
|
||||
*
|
||||
*/
|
||||
public class Excalibur extends BlindingMagicWeaponImpl {
|
||||
public class FlyingEnchantment implements Enchantment {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Excalibur.class);
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(FlyingEnchantment.class);
|
||||
|
||||
@Override
|
||||
public void wieldImp() {
|
||||
LOGGER.info("wielding Excalibur");
|
||||
public void onActivate() {
|
||||
LOGGER.info("The item begins to glow faintly.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swingImp() {
|
||||
LOGGER.info("swinging Excalibur");
|
||||
public void apply() {
|
||||
LOGGER.info("The item flies and strikes the enemies finally returning to owner's hand.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwieldImp() {
|
||||
LOGGER.info("unwielding Excalibur");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void blindImp() {
|
||||
LOGGER.info("bright light streams from Excalibur blinding the enemy");
|
||||
public void onDeactivate() {
|
||||
LOGGER.info("The item's glow fades.");
|
||||
}
|
||||
}
|
@ -22,38 +22,44 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* BlindingMagicWeapon
|
||||
* Hammer
|
||||
*
|
||||
*/
|
||||
public class BlindingMagicWeapon extends MagicWeapon {
|
||||
public class Hammer implements Weapon {
|
||||
|
||||
public BlindingMagicWeapon(BlindingMagicWeaponImpl imp) {
|
||||
super(imp);
|
||||
}
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Hammer.class);
|
||||
|
||||
@Override
|
||||
public BlindingMagicWeaponImpl getImp() {
|
||||
return (BlindingMagicWeaponImpl) imp;
|
||||
private final Enchantment enchantment;
|
||||
|
||||
public Hammer(Enchantment enchantment) {
|
||||
this.enchantment = enchantment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void wield() {
|
||||
getImp().wieldImp();
|
||||
LOGGER.info("The hammer is wielded.");
|
||||
enchantment.onActivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
getImp().swingImp();
|
||||
LOGGER.info("The hammer is swinged.");
|
||||
enchantment.apply();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwield() {
|
||||
getImp().unwieldImp();
|
||||
LOGGER.info("The hammer is unwielded.");
|
||||
enchantment.onDeactivate();
|
||||
}
|
||||
|
||||
public void blind() {
|
||||
getImp().blindImp();
|
||||
@Override
|
||||
public Enchantment getEnchantment() {
|
||||
return enchantment;
|
||||
}
|
||||
}
|
@ -27,30 +27,25 @@ import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* Stormbringer
|
||||
* SoulEatingEnchantment
|
||||
*
|
||||
*/
|
||||
public class Stormbringer extends SoulEatingMagicWeaponImpl {
|
||||
public class SoulEatingEnchantment implements Enchantment {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Stormbringer.class);
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(SoulEatingEnchantment.class);
|
||||
|
||||
@Override
|
||||
public void wieldImp() {
|
||||
LOGGER.info("wielding Stormbringer");
|
||||
public void onActivate() {
|
||||
LOGGER.info("The item spreads bloodlust.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swingImp() {
|
||||
LOGGER.info("swinging Stormbringer");
|
||||
public void apply() {
|
||||
LOGGER.info("The item eats the soul of enemies.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwieldImp() {
|
||||
LOGGER.info("unwielding Stormbringer");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void eatSoulImp() {
|
||||
LOGGER.info("Stormbringer devours the enemy's soul");
|
||||
public void onDeactivate() {
|
||||
LOGGER.info("Bloodlust slowly disappears.");
|
||||
}
|
||||
}
|
@ -22,39 +22,44 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
* SoulEatingMagicWeapon
|
||||
* Sword
|
||||
*
|
||||
*/
|
||||
public class SoulEatingMagicWeapon extends MagicWeapon {
|
||||
public class Sword implements Weapon {
|
||||
|
||||
public SoulEatingMagicWeapon(SoulEatingMagicWeaponImpl imp) {
|
||||
super(imp);
|
||||
}
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Sword.class);
|
||||
|
||||
@Override
|
||||
public SoulEatingMagicWeaponImpl getImp() {
|
||||
return (SoulEatingMagicWeaponImpl) imp;
|
||||
private final Enchantment enchantment;
|
||||
|
||||
public Sword(Enchantment enchantment) {
|
||||
this.enchantment = enchantment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void wield() {
|
||||
getImp().wieldImp();
|
||||
LOGGER.info("The sword is wielded.");
|
||||
enchantment.onActivate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
getImp().swingImp();
|
||||
LOGGER.info("The sword is swinged.");
|
||||
enchantment.apply();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwield() {
|
||||
getImp().unwieldImp();
|
||||
LOGGER.info("The sword is unwielded.");
|
||||
enchantment.onDeactivate();
|
||||
}
|
||||
|
||||
public void eatSoul() {
|
||||
getImp().eatSoulImp();
|
||||
@Override
|
||||
public Enchantment getEnchantment() {
|
||||
return enchantment;
|
||||
}
|
||||
|
||||
}
|
@ -24,11 +24,16 @@ package com.iluwatar.bridge;
|
||||
|
||||
/**
|
||||
*
|
||||
* BlindingMagicWeaponImpl
|
||||
*
|
||||
* Weapon
|
||||
*
|
||||
*/
|
||||
public abstract class BlindingMagicWeaponImpl extends MagicWeaponImpl {
|
||||
public interface Weapon {
|
||||
|
||||
public abstract void blindImp();
|
||||
void wield();
|
||||
|
||||
void swing();
|
||||
|
||||
void unwield();
|
||||
|
||||
Enchantment getEnchantment();
|
||||
}
|
@ -24,32 +24,22 @@ package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
/**
|
||||
* Date: 12/6/15 - 11:26 PM
|
||||
*
|
||||
* @author Jeroen Meulemeester
|
||||
* Tests for hammer
|
||||
*/
|
||||
public class FlyingMagicWeaponTest extends MagicWeaponTest {
|
||||
public class HammerTest extends WeaponTest {
|
||||
|
||||
/**
|
||||
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
|
||||
* underlying weapon implementation.
|
||||
*/
|
||||
@Test
|
||||
public void testMjollnir() throws Exception {
|
||||
final Mjollnir mjollnir = spy(new Mjollnir());
|
||||
final FlyingMagicWeapon flyingMagicWeapon = new FlyingMagicWeapon(mjollnir);
|
||||
|
||||
testBasicWeaponActions(flyingMagicWeapon, mjollnir);
|
||||
|
||||
flyingMagicWeapon.fly();
|
||||
verify(mjollnir, times(1)).flyImp();
|
||||
verifyNoMoreInteractions(mjollnir);
|
||||
public void testHammer() throws Exception {
|
||||
final Hammer hammer = spy(new Hammer(mock(FlyingEnchantment.class)));
|
||||
testBasicWeaponActions(hammer);
|
||||
}
|
||||
|
||||
}
|
@ -1,55 +0,0 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
/**
|
||||
* Date: 12/6/15 - 11:43 PM
|
||||
*
|
||||
* @author Jeroen Meulemeester
|
||||
*/
|
||||
public class SoulEatingMagicWeaponTest extends MagicWeaponTest {
|
||||
|
||||
/**
|
||||
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
|
||||
* underlying weapon implementation.
|
||||
*/
|
||||
@Test
|
||||
public void testStormBringer() throws Exception {
|
||||
final Stormbringer stormbringer = spy(new Stormbringer());
|
||||
final SoulEatingMagicWeapon soulEatingMagicWeapon = new SoulEatingMagicWeapon(stormbringer);
|
||||
|
||||
testBasicWeaponActions(soulEatingMagicWeapon, stormbringer);
|
||||
|
||||
soulEatingMagicWeapon.eatSoul();
|
||||
verify(stormbringer, times(1)).eatSoulImp();
|
||||
verifyNoMoreInteractions(stormbringer);
|
||||
}
|
||||
|
||||
}
|
@ -22,38 +22,24 @@
|
||||
*/
|
||||
package com.iluwatar.bridge;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.spy;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
*
|
||||
* FlyingMagicWeapon
|
||||
*
|
||||
* Tests for sword
|
||||
*/
|
||||
public class FlyingMagicWeapon extends MagicWeapon {
|
||||
public class SwordTest extends WeaponTest {
|
||||
|
||||
public FlyingMagicWeapon(FlyingMagicWeaponImpl imp) {
|
||||
super(imp);
|
||||
/**
|
||||
* Invoke all possible actions on the weapon and check if the actions are executed on the actual
|
||||
* underlying weapon implementation.
|
||||
*/
|
||||
@Test
|
||||
public void testSword() throws Exception {
|
||||
final Sword sword = spy(new Sword(mock(FlyingEnchantment.class)));
|
||||
testBasicWeaponActions(sword);
|
||||
}
|
||||
|
||||
public FlyingMagicWeaponImpl getImp() {
|
||||
return (FlyingMagicWeaponImpl) imp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void wield() {
|
||||
getImp().wieldImp();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
getImp().swingImp();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unwield() {
|
||||
getImp().unwieldImp();
|
||||
}
|
||||
|
||||
public void fly() {
|
||||
getImp().flyImp();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -28,37 +28,32 @@ import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.internal.verification.VerificationModeFactory.times;
|
||||
|
||||
/**
|
||||
* Date: 12/6/15 - 11:28 PM
|
||||
*
|
||||
* @author Jeroen Meulemeester
|
||||
* Base class for weapon tests
|
||||
*/
|
||||
public abstract class MagicWeaponTest {
|
||||
public abstract class WeaponTest {
|
||||
|
||||
/**
|
||||
* Invoke the basic actions of the given weapon, and test if the underlying weapon implementation
|
||||
* Invoke the basic actions of the given weapon, and test if the underlying enchantment implementation
|
||||
* is invoked
|
||||
*
|
||||
* @param weaponImpl The spied weapon implementation where actions are bridged to
|
||||
* @param weapon The weapon, handled by the app
|
||||
*/
|
||||
protected final void testBasicWeaponActions(final MagicWeapon weapon,
|
||||
final MagicWeaponImpl weaponImpl) {
|
||||
protected final void testBasicWeaponActions(final Weapon weapon) {
|
||||
assertNotNull(weapon);
|
||||
assertNotNull(weaponImpl);
|
||||
assertNotNull(weapon.getImp());
|
||||
Enchantment enchantment = weapon.getEnchantment();
|
||||
assertNotNull(enchantment);
|
||||
assertNotNull(weapon.getEnchantment());
|
||||
|
||||
weapon.swing();
|
||||
verify(weaponImpl, times(1)).swingImp();
|
||||
verifyNoMoreInteractions(weaponImpl);
|
||||
verify(enchantment).apply();
|
||||
verifyNoMoreInteractions(enchantment);
|
||||
|
||||
weapon.wield();
|
||||
verify(weaponImpl, times(1)).wieldImp();
|
||||
verifyNoMoreInteractions(weaponImpl);
|
||||
verify(enchantment).onActivate();
|
||||
verifyNoMoreInteractions(enchantment);
|
||||
|
||||
weapon.unwield();
|
||||
verify(weaponImpl, times(1)).unwieldImp();
|
||||
verifyNoMoreInteractions(weaponImpl);
|
||||
verify(enchantment).onDeactivate();
|
||||
verifyNoMoreInteractions(enchantment);
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -16,7 +16,103 @@ Separate the construction of a complex object from its
|
||||
representation so that the same construction process can create different
|
||||
representations.
|
||||
|
||||

|
||||
## Explanation
|
||||
|
||||
Real world example
|
||||
|
||||
> Imagine a character generator for a role playing game. The easiest option is to let computer create the character for you. But if you want to select the character details like profession, gender, hair color etc. the character generation becomes a step-by-step process that completes when all the selections are ready.
|
||||
|
||||
In plain words
|
||||
|
||||
> Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
|
||||
|
||||
Having said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other we have all seen a constructor like below:
|
||||
|
||||
```
|
||||
public Hero(Profession profession, String name, HairType hairType, HairColor hairColor, Armor armor, Weapon weapon) {
|
||||
}
|
||||
```
|
||||
|
||||
As you can see the number of constructor parameters can quickly get out of hand and it might become difficult to understand the arrangement of parameters. Plus this parameter list could keep on growing if you would want to add more options in future. This is called telescoping constructor anti-pattern.
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
The sane alternative is to use the Builder pattern. First of all we have our hero that we want to create
|
||||
|
||||
```
|
||||
public final class Hero {
|
||||
private final Profession profession;
|
||||
private final String name;
|
||||
private final HairType hairType;
|
||||
private final HairColor hairColor;
|
||||
private final Armor armor;
|
||||
private final Weapon weapon;
|
||||
|
||||
private Hero(Builder builder) {
|
||||
this.profession = builder.profession;
|
||||
this.name = builder.name;
|
||||
this.hairColor = builder.hairColor;
|
||||
this.hairType = builder.hairType;
|
||||
this.weapon = builder.weapon;
|
||||
this.armor = builder.armor;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And then we have the builder
|
||||
|
||||
```
|
||||
public static class Builder {
|
||||
private final Profession profession;
|
||||
private final String name;
|
||||
private HairType hairType;
|
||||
private HairColor hairColor;
|
||||
private Armor armor;
|
||||
private Weapon weapon;
|
||||
|
||||
public Builder(Profession profession, String name) {
|
||||
if (profession == null || name == null) {
|
||||
throw new IllegalArgumentException("profession and name can not be null");
|
||||
}
|
||||
this.profession = profession;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Builder withHairType(HairType hairType) {
|
||||
this.hairType = hairType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withHairColor(HairColor hairColor) {
|
||||
this.hairColor = hairColor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withArmor(Armor armor) {
|
||||
this.armor = armor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder withWeapon(Weapon weapon) {
|
||||
this.weapon = weapon;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Hero build() {
|
||||
return new Hero(this);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And then it can be used as:
|
||||
|
||||
```
|
||||
Hero mage = new Hero.Builder(Profession.MAGE, "Riobard").withHairColor(HairColor.BLACK).withWeapon(Weapon.DAGGER).build();
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use the Builder pattern when
|
||||
|
Before Width: | Height: | Size: 52 KiB |
@ -1,162 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
||||
<enumeration id="1" language="java" name="com.iluwatar.builder.HairType" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/HairType.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="214" width="189" x="177" y="419"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<enumeration id="2" language="java" name="com.iluwatar.builder.Weapon" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/Weapon.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="196" width="171" x="406" y="419"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<enumeration id="3" language="java" name="com.iluwatar.builder.HairColor" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/HairColor.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="196" width="144" x="-204" y="419"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<class id="4" language="java" name="com.iluwatar.builder.Hero.Builder" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/Hero.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="196" width="234" x="20" y="183"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<enumeration id="5" language="java" name="com.iluwatar.builder.Armor" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/Armor.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="196" width="145" x="617" y="419"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<enumeration id="6" language="java" name="com.iluwatar.builder.Profession" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/Profession.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="178" width="157" x="-20" y="419"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<class id="7" language="java" name="com.iluwatar.builder.Hero" project="builder"
|
||||
file="/builder/src/main/java/com/iluwatar/builder/Hero.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="232" width="178" x="275" y="-89"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<association id="8">
|
||||
<bendpoint x="284" y="183"/>
|
||||
<end type="SOURCE" refId="7" navigable="false">
|
||||
<attribute id="9" name="hairType"/>
|
||||
<multiplicity id="10" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="1" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="11">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="12" name="weapon"/>
|
||||
<multiplicity id="13" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="2" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="14">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="15" name="profession"/>
|
||||
<multiplicity id="16" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="6" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="17">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="18" name="hairColor"/>
|
||||
<multiplicity id="19" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="3" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="20">
|
||||
<bendpoint x="350" y="183"/>
|
||||
<end type="SOURCE" refId="7" navigable="false">
|
||||
<attribute id="21" name="weapon"/>
|
||||
<multiplicity id="22" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="2" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="23">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="24" name="hairType"/>
|
||||
<multiplicity id="25" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="1" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<nesting id="26">
|
||||
<end type="SOURCE" refId="7"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</nesting>
|
||||
<association id="27">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="28" name="armor"/>
|
||||
<multiplicity id="29" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="5" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="30">
|
||||
<bendpoint x="-11" y="183"/>
|
||||
<end type="SOURCE" refId="7" navigable="false">
|
||||
<attribute id="31" name="profession"/>
|
||||
<multiplicity id="32" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="6" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="33">
|
||||
<bendpoint x="-32" y="183"/>
|
||||
<end type="SOURCE" refId="7" navigable="false">
|
||||
<attribute id="34" name="hairColor"/>
|
||||
<multiplicity id="35" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="3" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="36">
|
||||
<bendpoint x="455" y="183"/>
|
||||
<end type="SOURCE" refId="7" navigable="false">
|
||||
<attribute id="37" name="armor"/>
|
||||
<multiplicity id="38" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="5" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
@ -1,100 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.builder {
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
enum Armor {
|
||||
+ CHAIN_MAIL {static}
|
||||
+ CLOTHES {static}
|
||||
+ LEATHER {static}
|
||||
+ PLATE_MAIL {static}
|
||||
- title : String
|
||||
+ toString() : String
|
||||
+ valueOf(name : String) : Armor {static}
|
||||
+ values() : Armor[] {static}
|
||||
}
|
||||
enum HairColor {
|
||||
+ BLACK {static}
|
||||
+ BLOND {static}
|
||||
+ BROWN {static}
|
||||
+ RED {static}
|
||||
+ WHITE {static}
|
||||
+ toString() : String
|
||||
+ valueOf(name : String) : HairColor {static}
|
||||
+ values() : HairColor[] {static}
|
||||
}
|
||||
enum HairType {
|
||||
+ BALD {static}
|
||||
+ CURLY {static}
|
||||
+ LONG_CURLY {static}
|
||||
+ LONG_STRAIGHT {static}
|
||||
+ SHORT {static}
|
||||
- title : String
|
||||
+ toString() : String
|
||||
+ valueOf(name : String) : HairType {static}
|
||||
+ values() : HairType[] {static}
|
||||
}
|
||||
class Hero {
|
||||
- armor : Armor
|
||||
- hairColor : HairColor
|
||||
- hairType : HairType
|
||||
- name : String
|
||||
- profession : Profession
|
||||
- weapon : Weapon
|
||||
- Hero(builder : Builder)
|
||||
+ getArmor() : Armor
|
||||
+ getHairColor() : HairColor
|
||||
+ getHairType() : HairType
|
||||
+ getName() : String
|
||||
+ getProfession() : Profession
|
||||
+ getWeapon() : Weapon
|
||||
+ toString() : String
|
||||
}
|
||||
class Builder {
|
||||
- armor : Armor
|
||||
- hairColor : HairColor
|
||||
- hairType : HairType
|
||||
- name : String
|
||||
- profession : Profession
|
||||
- weapon : Weapon
|
||||
+ Builder(profession : Profession, name : String)
|
||||
+ build() : Hero
|
||||
+ withArmor(armor : Armor) : Builder
|
||||
+ withHairColor(hairColor : HairColor) : Builder
|
||||
+ withHairType(hairType : HairType) : Builder
|
||||
+ withWeapon(weapon : Weapon) : Builder
|
||||
}
|
||||
enum Profession {
|
||||
+ MAGE {static}
|
||||
+ PRIEST {static}
|
||||
+ THIEF {static}
|
||||
+ WARRIOR {static}
|
||||
+ toString() : String
|
||||
+ valueOf(name : String) : Profession {static}
|
||||
+ values() : Profession[] {static}
|
||||
}
|
||||
enum Weapon {
|
||||
+ AXE {static}
|
||||
+ BOW {static}
|
||||
+ DAGGER {static}
|
||||
+ SWORD {static}
|
||||
+ WARHAMMER {static}
|
||||
+ toString() : String
|
||||
+ valueOf(name : String) : Weapon {static}
|
||||
+ values() : Weapon[] {static}
|
||||
}
|
||||
}
|
||||
Builder ..+ Hero
|
||||
Hero --> "-profession" Profession
|
||||
Hero --> "-armor" Armor
|
||||
Builder --> "-hairColor" HairColor
|
||||
Builder --> "-weapon" Weapon
|
||||
Builder --> "-hairType" HairType
|
||||
Hero --> "-hairColor" HairColor
|
||||
Builder --> "-profession" Profession
|
||||
Hero --> "-hairType" HairType
|
||||
Hero --> "-weapon" Weapon
|
||||
Builder --> "-armor" Armor
|
||||
@enduml
|
Before Width: | Height: | Size: 104 KiB |
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>builder</artifactId>
|
||||
<dependencies>
|
||||
|
@ -30,7 +30,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>business-delegate</artifactId>
|
||||
<dependencies>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>caching</artifactId>
|
||||
<dependencies>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>callback</artifactId>
|
||||
<dependencies>
|
||||
|
126
chain/README.md
@ -16,7 +16,131 @@ Avoid coupling the sender of a request to its receiver by giving
|
||||
more than one object a chance to handle the request. Chain the receiving
|
||||
objects and pass the request along the chain until an object handles it.
|
||||
|
||||

|
||||
## Explanation
|
||||
|
||||
Real world example
|
||||
|
||||
> The Orc King gives loud orders to his army. The closest one to react is the commander, then officer and then soldier. The commander, officer and soldier here form a chain of responsibility.
|
||||
|
||||
In plain words
|
||||
|
||||
> It helps building a chain of objects. Request enters from one end and keeps going from object to object till it finds the suitable handler.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
Translating our example with orcs from above. First we have the request class
|
||||
|
||||
```
|
||||
public class Request {
|
||||
|
||||
private final RequestType requestType;
|
||||
private final String requestDescription;
|
||||
private boolean handled;
|
||||
|
||||
public Request(final RequestType requestType, final String requestDescription) {
|
||||
this.requestType = Objects.requireNonNull(requestType);
|
||||
this.requestDescription = Objects.requireNonNull(requestDescription);
|
||||
}
|
||||
|
||||
public String getRequestDescription() { return requestDescription; }
|
||||
|
||||
public RequestType getRequestType() { return requestType; }
|
||||
|
||||
public void markHandled() { this.handled = true; }
|
||||
|
||||
public boolean isHandled() { return this.handled; }
|
||||
|
||||
@Override
|
||||
public String toString() { return getRequestDescription(); }
|
||||
}
|
||||
|
||||
public enum RequestType {
|
||||
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
|
||||
}
|
||||
```
|
||||
|
||||
Then the request handler hierarchy
|
||||
|
||||
```
|
||||
public abstract class RequestHandler {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
|
||||
private RequestHandler next;
|
||||
|
||||
public RequestHandler(RequestHandler next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public void handleRequest(Request req) {
|
||||
if (next != null) {
|
||||
next.handleRequest(req);
|
||||
}
|
||||
}
|
||||
|
||||
protected void printHandling(Request req) {
|
||||
LOGGER.info("{} handling request \"{}\"", this, req);
|
||||
}
|
||||
|
||||
@Override
|
||||
public abstract String toString();
|
||||
}
|
||||
|
||||
public class OrcCommander extends RequestHandler {
|
||||
public OrcCommander(RequestHandler handler) {
|
||||
super(handler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleRequest(Request req) {
|
||||
if (req.getRequestType().equals(RequestType.DEFEND_CASTLE)) {
|
||||
printHandling(req);
|
||||
req.markHandled();
|
||||
} else {
|
||||
super.handleRequest(req);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Orc commander";
|
||||
}
|
||||
}
|
||||
|
||||
// OrcOfficer and OrcSoldier are defined similarly as OrcCommander
|
||||
|
||||
```
|
||||
|
||||
Then we have the Orc King who gives the orders and forms the chain
|
||||
|
||||
```
|
||||
public class OrcKing {
|
||||
RequestHandler chain;
|
||||
|
||||
public OrcKing() {
|
||||
buildChain();
|
||||
}
|
||||
|
||||
private void buildChain() {
|
||||
chain = new OrcCommander(new OrcOfficer(new OrcSoldier(null)));
|
||||
}
|
||||
|
||||
public void makeRequest(Request req) {
|
||||
chain.handleRequest(req);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then it is used as follows
|
||||
|
||||
```
|
||||
OrcKing king = new OrcKing();
|
||||
king.makeRequest(new Request(RequestType.DEFEND_CASTLE, "defend castle")); // Orc commander handling request "defend castle"
|
||||
king.makeRequest(new Request(RequestType.TORTURE_PRISONER, "torture prisoner")); // Orc officer handling request "torture prisoner"
|
||||
king.makeRequest(new Request(RequestType.COLLECT_TAX, "collect tax")); // Orc soldier handling request "collect tax"
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use Chain of Responsibility when
|
||||
|
Before Width: | Height: | Size: 30 KiB |
@ -1,109 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
||||
<class id="1" language="java" name="com.iluwatar.chain.Request" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/Request.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="196" width="228" x="168" y="182"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="2" language="java" name="com.iluwatar.chain.OrcOfficer" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/OrcOfficer.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="194" x="168" y="609"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="3" language="java" name="com.iluwatar.chain.OrcCommander" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/OrcCommander.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="217" x="402" y="609"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="4" language="java" name="com.iluwatar.chain.RequestHandler" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/RequestHandler.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="141" width="218" x="451" y="418"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="5" language="java" name="com.iluwatar.chain.OrcSoldier" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/OrcSoldier.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="194" x="659" y="609"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="6" language="java" name="com.iluwatar.chain.OrcKing" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/OrcKing.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="188" x="451" y="182"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<enumeration id="7" language="java" name="com.iluwatar.chain.RequestType" project="chain"
|
||||
file="/chain/src/main/java/com/iluwatar/chain/RequestType.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="142" width="243" x="168" y="418"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</enumeration>
|
||||
<association id="8">
|
||||
<end type="SOURCE" refId="6" navigable="false">
|
||||
<attribute id="9" name="chain"/>
|
||||
<multiplicity id="10" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="4" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<association id="11">
|
||||
<end type="SOURCE" refId="4" navigable="false">
|
||||
<attribute id="12" name="next"/>
|
||||
<multiplicity id="13" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="4" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<generalization id="14">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<association id="15">
|
||||
<end type="SOURCE" refId="1" navigable="false">
|
||||
<attribute id="16" name="requestType"/>
|
||||
<multiplicity id="17" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="7" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<generalization id="18">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<generalization id="19">
|
||||
<end type="SOURCE" refId="3"/>
|
||||
<end type="TARGET" refId="4"/>
|
||||
</generalization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
@ -1,61 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.chain {
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class OrcCommander {
|
||||
+ OrcCommander(handler : RequestHandler)
|
||||
+ handleRequest(req : Request)
|
||||
+ toString() : String
|
||||
}
|
||||
class OrcKing {
|
||||
~ chain : RequestHandler
|
||||
+ OrcKing()
|
||||
- buildChain()
|
||||
+ makeRequest(req : Request)
|
||||
}
|
||||
class OrcOfficer {
|
||||
+ OrcOfficer(handler : RequestHandler)
|
||||
+ handleRequest(req : Request)
|
||||
+ toString() : String
|
||||
}
|
||||
class OrcSoldier {
|
||||
+ OrcSoldier(handler : RequestHandler)
|
||||
+ handleRequest(req : Request)
|
||||
+ toString() : String
|
||||
}
|
||||
class Request {
|
||||
- handled : boolean
|
||||
- requestDescription : String
|
||||
- requestType : RequestType
|
||||
+ Request(requestType : RequestType, requestDescription : String)
|
||||
+ getRequestDescription() : String
|
||||
+ getRequestType() : RequestType
|
||||
+ isHandled() : boolean
|
||||
+ markHandled()
|
||||
+ toString() : String
|
||||
}
|
||||
abstract class RequestHandler {
|
||||
- LOGGER : Logger {static}
|
||||
- next : RequestHandler
|
||||
+ RequestHandler(next : RequestHandler)
|
||||
+ handleRequest(req : Request)
|
||||
# printHandling(req : Request)
|
||||
+ toString() : String {abstract}
|
||||
}
|
||||
enum RequestType {
|
||||
+ COLLECT_TAX {static}
|
||||
+ DEFEND_CASTLE {static}
|
||||
+ TORTURE_PRISONER {static}
|
||||
+ valueOf(name : String) : RequestType {static}
|
||||
+ values() : RequestType[] {static}
|
||||
}
|
||||
}
|
||||
RequestHandler --> "-next" RequestHandler
|
||||
Request --> "-requestType" RequestType
|
||||
OrcKing --> "-chain" RequestHandler
|
||||
OrcCommander --|> RequestHandler
|
||||
OrcOfficer --|> RequestHandler
|
||||
OrcSoldier --|> RequestHandler
|
||||
@enduml
|
Before Width: | Height: | Size: 60 KiB |
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>chain</artifactId>
|
||||
<dependencies>
|
||||
|
@ -85,9 +85,7 @@
|
||||
value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, LITERAL_SWITCH"/>
|
||||
</module>
|
||||
<module name="NeedBraces"/>
|
||||
<module name="LeftCurly">
|
||||
<property name="maxLineLength" value="120"/>
|
||||
</module>
|
||||
<module name="LeftCurly"/>
|
||||
<module name="RightCurly"/>
|
||||
<module name="RightCurly">
|
||||
<property name="option" value="alone"/>
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>command</artifactId>
|
||||
<dependencies>
|
||||
|
@ -29,7 +29,7 @@ package com.iluwatar.command;
|
||||
*/
|
||||
public enum Size {
|
||||
|
||||
SMALL("small"), NORMAL("normal"), LARGE("large"), UNDEFINED("");
|
||||
SMALL("small"), NORMAL("normal");
|
||||
|
||||
private String title;
|
||||
|
||||
|
@ -29,7 +29,7 @@ package com.iluwatar.command;
|
||||
*/
|
||||
public enum Visibility {
|
||||
|
||||
VISIBLE("visible"), INVISIBLE("invisible"), UNDEFINED("");
|
||||
VISIBLE("visible"), INVISIBLE("invisible");
|
||||
|
||||
private String title;
|
||||
|
||||
|
@ -40,7 +40,9 @@ public class Wizard {
|
||||
private Deque<Command> undoStack = new LinkedList<>();
|
||||
private Deque<Command> redoStack = new LinkedList<>();
|
||||
|
||||
public Wizard() {}
|
||||
public Wizard() {
|
||||
// comment to ignore sonar issue: LEVEL critical
|
||||
}
|
||||
|
||||
/**
|
||||
* Cast spell
|
||||
|
@ -16,7 +16,119 @@ Compose objects into tree structures to represent part-whole
|
||||
hierarchies. Composite lets clients treat individual objects and compositions
|
||||
of objects uniformly.
|
||||
|
||||

|
||||
## Explanation
|
||||
|
||||
Real world example
|
||||
|
||||
> Every sentence is composed of words which are in turn composed of characters. Each of these objects is printable and they can have something printed before or after them like sentence always ends with full stop and word always has space before it
|
||||
|
||||
In plain words
|
||||
|
||||
> Composite pattern lets clients treat the individual objects in a uniform manner.
|
||||
|
||||
Wikipedia says
|
||||
|
||||
> In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
|
||||
|
||||
**Programmatic Example**
|
||||
|
||||
Taking our sentence example from above. Here we have the base class and different printable types
|
||||
|
||||
```
|
||||
public abstract class LetterComposite {
|
||||
private List<LetterComposite> children = new ArrayList<>();
|
||||
public void add(LetterComposite letter) {
|
||||
children.add(letter);
|
||||
}
|
||||
public int count() {
|
||||
return children.size();
|
||||
}
|
||||
protected void printThisBefore() {}
|
||||
protected void printThisAfter() {}
|
||||
public void print() {
|
||||
printThisBefore();
|
||||
for (LetterComposite letter : children) {
|
||||
letter.print();
|
||||
}
|
||||
printThisAfter();
|
||||
}
|
||||
}
|
||||
|
||||
public class Letter extends LetterComposite {
|
||||
private char c;
|
||||
public Letter(char c) {
|
||||
this.c = c;
|
||||
}
|
||||
@Override
|
||||
protected void printThisBefore() {
|
||||
System.out.print(c);
|
||||
}
|
||||
}
|
||||
|
||||
public class Word extends LetterComposite {
|
||||
public Word(List<Letter> letters) {
|
||||
for (Letter l : letters) {
|
||||
this.add(l);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void printThisBefore() {
|
||||
System.out.print(" ");
|
||||
}
|
||||
}
|
||||
|
||||
public class Sentence extends LetterComposite {
|
||||
public Sentence(List<Word> words) {
|
||||
for (Word w : words) {
|
||||
this.add(w);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected void printThisAfter() {
|
||||
System.out.print(".");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then we have a messenger to carry messages
|
||||
|
||||
```
|
||||
public class Messenger {
|
||||
LetterComposite messageFromOrcs() {
|
||||
List<Word> words = new ArrayList<>();
|
||||
words.add(new Word(Arrays.asList(new Letter('W'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('a'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('h'), new Letter('i'), new Letter('p'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('t'), new Letter('h'), new Letter('e'), new Letter('r'), new Letter('e'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('i'), new Letter('s'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('a'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('a'), new Letter('y'))));
|
||||
return new Sentence(words);
|
||||
}
|
||||
|
||||
LetterComposite messageFromElves() {
|
||||
List<Word> words = new ArrayList<>();
|
||||
words.add(new Word(Arrays.asList(new Letter('M'), new Letter('u'), new Letter('c'), new Letter('h'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('w'), new Letter('i'), new Letter('n'), new Letter('d'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('p'), new Letter('o'), new Letter('u'), new Letter('r'), new Letter('s'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('f'), new Letter('r'), new Letter('o'), new Letter('m'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('y'), new Letter('o'), new Letter('u'), new Letter('r'))));
|
||||
words.add(new Word(Arrays.asList(new Letter('m'), new Letter('o'), new Letter('u'), new Letter('t'), new Letter('h'))));
|
||||
return new Sentence(words);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
And then it can be used as
|
||||
|
||||
```
|
||||
LetterComposite orcMessage = new Messenger().messageFromOrcs();
|
||||
orcMessage.print(); // Where there is a whip there is a way.
|
||||
LetterComposite elfMessage = new Messenger().messageFromElves();
|
||||
elfMessage.print(); // Much wind pours from your mouth.
|
||||
```
|
||||
|
||||
## Applicability
|
||||
Use the Composite pattern when
|
||||
|
Before Width: | Height: | Size: 16 KiB |
@ -1,75 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
|
||||
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
|
||||
<class id="1" language="java" name="com.iluwatar.composite.Messenger" project="composite"
|
||||
file="/composite/src/main/java/com/iluwatar/composite/Messenger.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="247" x="118" y="180"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="2" language="java" name="com.iluwatar.composite.Sentence" project="composite"
|
||||
file="/composite/src/main/java/com/iluwatar/composite/Sentence.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="157" x="118" y="407"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="3" language="java" name="com.iluwatar.composite.LetterComposite" project="composite"
|
||||
file="/composite/src/main/java/com/iluwatar/composite/LetterComposite.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="177" width="176" x="405" y="180"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="4" language="java" name="com.iluwatar.composite.Letter" project="composite"
|
||||
file="/composite/src/main/java/com/iluwatar/composite/Letter.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="142" width="146" x="315" y="407"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="5" language="java" name="com.iluwatar.composite.Word" project="composite"
|
||||
file="/composite/src/main/java/com/iluwatar/composite/Word.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="124" width="146" x="501" y="407"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<generalization id="6">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
</generalization>
|
||||
<generalization id="7">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
</generalization>
|
||||
<association id="8">
|
||||
<end type="SOURCE" refId="3" navigable="false">
|
||||
<attribute id="9" name="children"/>
|
||||
<multiplicity id="10" minimum="0" maximum="2147483647"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="3" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<generalization id="11">
|
||||
<end type="SOURCE" refId="5"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
</generalization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
@ -1,43 +0,0 @@
|
||||
@startuml
|
||||
package com.iluwatar.composite {
|
||||
class App {
|
||||
- LOGGER : Logger {static}
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
class Letter {
|
||||
- c : char
|
||||
+ Letter(c : char)
|
||||
# printThisAfter()
|
||||
# printThisBefore()
|
||||
}
|
||||
abstract class LetterComposite {
|
||||
- children : List<LetterComposite>
|
||||
+ LetterComposite()
|
||||
+ add(letter : LetterComposite)
|
||||
+ count() : int
|
||||
+ print()
|
||||
# printThisAfter() {abstract}
|
||||
# printThisBefore() {abstract}
|
||||
}
|
||||
class Messenger {
|
||||
+ Messenger()
|
||||
~ messageFromElves() : LetterComposite
|
||||
~ messageFromOrcs() : LetterComposite
|
||||
}
|
||||
class Sentence {
|
||||
+ Sentence(words : List<Word>)
|
||||
# printThisAfter()
|
||||
# printThisBefore()
|
||||
}
|
||||
class Word {
|
||||
+ Word(letters : List<Letter>)
|
||||
# printThisAfter()
|
||||
# printThisBefore()
|
||||
}
|
||||
}
|
||||
LetterComposite --> "-children" LetterComposite
|
||||
Letter --|> LetterComposite
|
||||
Sentence --|> LetterComposite
|
||||
Word --|> LetterComposite
|
||||
@enduml
|
Before Width: | Height: | Size: 33 KiB |
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>composite</artifactId>
|
||||
<dependencies>
|
||||
|
@ -51,9 +51,7 @@ public class App {
|
||||
LetterComposite orcMessage = new Messenger().messageFromOrcs();
|
||||
orcMessage.print();
|
||||
|
||||
LOGGER.info("\n");
|
||||
|
||||
LOGGER.info("Message from the elves: ");
|
||||
LOGGER.info("\nMessage from the elves: ");
|
||||
|
||||
LetterComposite elfMessage = new Messenger().messageFromElves();
|
||||
elfMessage.print();
|
||||
|
@ -39,9 +39,4 @@ public class Letter extends LetterComposite {
|
||||
protected void printThisBefore() {
|
||||
System.out.print(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void printThisAfter() {
|
||||
// nop
|
||||
}
|
||||
}
|
||||
|
@ -42,9 +42,9 @@ public abstract class LetterComposite {
|
||||
return children.size();
|
||||
}
|
||||
|
||||
protected abstract void printThisBefore();
|
||||
protected void printThisBefore() {}
|
||||
|
||||
protected abstract void printThisAfter();
|
||||
protected void printThisAfter() {}
|
||||
|
||||
/**
|
||||
* Print
|
||||
|
@ -40,11 +40,6 @@ public class Sentence extends LetterComposite {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void printThisBefore() {
|
||||
// nop
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void printThisAfter() {
|
||||
System.out.print(".");
|
||||
|
@ -44,9 +44,4 @@ public class Word extends LetterComposite {
|
||||
protected void printThisBefore() {
|
||||
System.out.print(" ");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void printThisAfter() {
|
||||
// nop
|
||||
}
|
||||
}
|
||||
|
@ -29,7 +29,7 @@
|
||||
<parent>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<version>1.16.0</version>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<dependencies>
|
||||
|
29
cqrs/README.md
Normal file
@ -0,0 +1,29 @@
|
||||
---
|
||||
layout: pattern
|
||||
title: CQRS
|
||||
folder: cqrs
|
||||
permalink: /patterns/cqrs/
|
||||
pumlid: 7SPR4a0m3030gt00pR_RH6I8QQFouFgC_TfHb6gkd5Q7FQBx363ub4rYpoMTZKuDrYXqDX37HIuuyCPfPPTDfuuHREhGqBy0NUR0GNzAMYizMtq1
|
||||
categories: Architectural
|
||||
tags:
|
||||
- Java
|
||||
- Difficulty-Intermediate
|
||||
---
|
||||
|
||||
## Intent
|
||||
CQRS Command Query Responsibility Segregation - Separate the query side from the command side.
|
||||
|
||||

|
||||
|
||||
## Applicability
|
||||
Use the CQRS pattern when
|
||||
|
||||
* you want to scale the queries and commands independently.
|
||||
* you want to use different data models for queries and commands. Useful when dealing with complex domains.
|
||||
* you want to use architectures like event sourcing or task based UI.
|
||||
|
||||
## Credits
|
||||
|
||||
* [Greg Young - CQRS, Task Based UIs, Event Sourcing agh!](http://codebetter.com/gregyoung/2010/02/16/cqrs-task-based-uis-event-sourcing-agh/)
|
||||
* [Martin Fowler - CQRS](https://martinfowler.com/bliki/CQRS.html)
|
||||
* [Oliver Wolf - CQRS for Great Good](https://www.youtube.com/watch?v=Ge53swja9Dw)
|
BIN
cqrs/etc/cqrs.png
Normal file
After Width: | Height: | Size: 103 KiB |
115
cqrs/etc/cqrs.ucls
Normal file
@ -0,0 +1,115 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<class-diagram version="1.2.0" icons="true" always-add-relationships="false" generalizations="true" realizations="true"
|
||||
associations="true" dependencies="false" nesting-relationships="true" router="FAN">
|
||||
<interface id="1" language="java" name="com.iluwatar.cqrs.commandes.ICommandService" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/commandes/ICommandService.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="291" y="-49"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<class id="2" language="java" name="com.iluwatar.cqrs.commandes.CommandServiceImpl" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/commandes/CommandServiceImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="263" width="256" x="170" y="87"/>
|
||||
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<interface id="3" language="java" name="com.iluwatar.cqrs.queries.IQueryService" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/queries/IQueryService.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="182" width="248" x="176" y="428"/>
|
||||
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</interface>
|
||||
<class id="4" language="java" name="com.iluwatar.cqrs.queries.QueryServiceImpl" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/queries/QueryServiceImpl.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="258" width="253" x="169" y="665"/>
|
||||
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="5" language="java" name="com.iluwatar.cqrs.domain.model.Book" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="326" width="158" x="778" y="-93"/>
|
||||
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="6" language="java" name="com.iluwatar.cqrs.dto.Book" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="219" width="150" x="541" y="607"/>
|
||||
<display autosize="false" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="7" language="java" name="com.iluwatar.cqrs.domain.model.Author" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="608" y="70"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="8" language="java" name="com.iluwatar.cqrs.dto.Author" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="834" y="719"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<class id="9" language="java" name="com.iluwatar.cqrs.util.HibernateUtil" project="cqrs"
|
||||
file="/cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java" binary="false" corner="BOTTOM_RIGHT">
|
||||
<position height="-1" width="-1" x="662" y="412"/>
|
||||
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</display>
|
||||
</class>
|
||||
<dependency id="10">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="9"/>
|
||||
</dependency>
|
||||
<dependency id="11">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="9"/>
|
||||
</dependency>
|
||||
<realization id="12">
|
||||
<end type="SOURCE" refId="4"/>
|
||||
<end type="TARGET" refId="3"/>
|
||||
</realization>
|
||||
<association id="13">
|
||||
<end type="SOURCE" refId="5" navigable="false">
|
||||
<attribute id="14" name="author"/>
|
||||
<multiplicity id="15" minimum="0" maximum="1"/>
|
||||
</end>
|
||||
<end type="TARGET" refId="7" navigable="true"/>
|
||||
<display labels="true" multiplicity="true"/>
|
||||
</association>
|
||||
<realization id="16">
|
||||
<end type="SOURCE" refId="2"/>
|
||||
<end type="TARGET" refId="1"/>
|
||||
</realization>
|
||||
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
|
||||
sort-features="false" accessors="true" visibility="true">
|
||||
<attributes public="true" package="true" protected="true" private="true" static="true"/>
|
||||
<operations public="true" package="true" protected="true" private="true" static="true"/>
|
||||
</classifier-display>
|
||||
<association-display labels="true" multiplicity="true"/>
|
||||
</class-diagram>
|
124
cqrs/etc/cqrs.urm.puml
Normal file
@ -0,0 +1,124 @@
|
||||
@startuml
|
||||
package com.iluwatar.cqrs.util {
|
||||
class HibernateUtil {
|
||||
- LOGGER : Logger {static}
|
||||
- SESSIONFACTORY : SessionFactory {static}
|
||||
+ HibernateUtil()
|
||||
- buildSessionFactory() : SessionFactory {static}
|
||||
+ getSessionFactory() : SessionFactory {static}
|
||||
}
|
||||
}
|
||||
package com.iluwatar.cqrs.app {
|
||||
class App {
|
||||
+ App()
|
||||
+ main(args : String[]) {static}
|
||||
}
|
||||
}
|
||||
package com.iluwatar.cqrs.dto {
|
||||
class Author {
|
||||
- email : String
|
||||
- name : String
|
||||
- username : String
|
||||
+ Author()
|
||||
+ Author(name : String, email : String, username : String)
|
||||
+ equals(obj : Object) : boolean
|
||||
+ getEmail() : String
|
||||
+ getName() : String
|
||||
+ getUsername() : String
|
||||
+ hashCode() : int
|
||||
+ toString() : String
|
||||
}
|
||||
class Book {
|
||||
- price : double
|
||||
- title : String
|
||||
+ Book()
|
||||
+ Book(title : String, price : double)
|
||||
+ equals(obj : Object) : boolean
|
||||
+ getPrice() : double
|
||||
+ getTitle() : String
|
||||
+ hashCode() : int
|
||||
+ toString() : String
|
||||
}
|
||||
}
|
||||
package com.iluwatar.cqrs.commandes {
|
||||
class CommandServiceImpl {
|
||||
- sessionFactory : SessionFactory
|
||||
+ CommandServiceImpl()
|
||||
+ authorCreated(username : String, name : String, email : String)
|
||||
+ authorEmailUpdated(username : String, email : String)
|
||||
+ authorNameUpdated(username : String, name : String)
|
||||
+ authorUsernameUpdated(oldUsername : String, newUsername : String)
|
||||
+ bookAddedToAuthor(title : String, price : double, username : String)
|
||||
+ bookPriceUpdated(title : String, price : double)
|
||||
+ bookTitleUpdated(oldTitle : String, newTitle : String)
|
||||
- getAuthorByUsername(username : String) : Author
|
||||
- getBookByTitle(title : String) : Book
|
||||
}
|
||||
interface ICommandService {
|
||||
+ authorCreated(String, String, String) {abstract}
|
||||
+ authorEmailUpdated(String, String) {abstract}
|
||||
+ authorNameUpdated(String, String) {abstract}
|
||||
+ authorUsernameUpdated(String, String) {abstract}
|
||||
+ bookAddedToAuthor(String, double, String) {abstract}
|
||||
+ bookPriceUpdated(String, double) {abstract}
|
||||
+ bookTitleUpdated(String, String) {abstract}
|
||||
}
|
||||
}
|
||||
package com.iluwatar.cqrs.queries {
|
||||
interface IQueryService {
|
||||
+ getAuthorBooks(String) : List<Book> {abstract}
|
||||
+ getAuthorBooksCount(String) : BigInteger {abstract}
|
||||
+ getAuthorByUsername(String) : Author {abstract}
|
||||
+ getAuthorsCount() : BigInteger {abstract}
|
||||
+ getBook(String) : Book {abstract}
|
||||
}
|
||||
class QueryServiceImpl {
|
||||
- sessionFactory : SessionFactory
|
||||
+ QueryServiceImpl()
|
||||
+ getAuthorBooks(username : String) : List<Book>
|
||||
+ getAuthorBooksCount(username : String) : BigInteger
|
||||
+ getAuthorByUsername(username : String) : Author
|
||||
+ getAuthorsCount() : BigInteger
|
||||
+ getBook(title : String) : Book
|
||||
}
|
||||
}
|
||||
package com.iluwatar.cqrs.domain.model {
|
||||
class Author {
|
||||
- email : String
|
||||
- id : long
|
||||
- name : String
|
||||
- username : String
|
||||
# Author()
|
||||
+ Author(username : String, name : String, email : String)
|
||||
+ getEmail() : String
|
||||
+ getId() : long
|
||||
+ getName() : String
|
||||
+ getUsername() : String
|
||||
+ setEmail(email : String)
|
||||
+ setId(id : long)
|
||||
+ setName(name : String)
|
||||
+ setUsername(username : String)
|
||||
+ toString() : String
|
||||
}
|
||||
class Book {
|
||||
- author : Author
|
||||
- id : long
|
||||
- price : double
|
||||
- title : String
|
||||
# Book()
|
||||
+ Book(title : String, price : double, author : Author)
|
||||
+ getAuthor() : Author
|
||||
+ getId() : long
|
||||
+ getPrice() : double
|
||||
+ getTitle() : String
|
||||
+ setAuthor(author : Author)
|
||||
+ setId(id : long)
|
||||
+ setPrice(price : double)
|
||||
+ setTitle(title : String)
|
||||
+ toString() : String
|
||||
}
|
||||
}
|
||||
Book --> "-author" Author
|
||||
CommandServiceImpl ..|> ICommandService
|
||||
QueryServiceImpl ..|> IQueryService
|
||||
@enduml
|
42
cqrs/pom.xml
Normal file
@ -0,0 +1,42 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- The MIT License Copyright (c) 2014-2016 Ilkka Seppälä Permission is
|
||||
hereby granted, free of charge, to any person obtaining a copy of this software
|
||||
and associated documentation files (the "Software"), to deal in the Software
|
||||
without restriction, including without limitation the rights to use, copy,
|
||||
modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions: The above copyright notice and this
|
||||
permission notice shall be included in all copies or substantial portions
|
||||
of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
|
||||
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
|
||||
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE. -->
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.17.0</version>
|
||||
</parent>
|
||||
<artifactId>cqrs</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
95
cqrs/src/main/java/com/iluwatar/cqrs/app/App.java
Normal file
@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014-2016 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.app;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
|
||||
import com.iluwatar.cqrs.commandes.ICommandService;
|
||||
import com.iluwatar.cqrs.dto.Author;
|
||||
import com.iluwatar.cqrs.dto.Book;
|
||||
import com.iluwatar.cqrs.queries.IQueryService;
|
||||
import com.iluwatar.cqrs.queries.QueryServiceImpl;
|
||||
import com.iluwatar.cqrs.util.HibernateUtil;
|
||||
|
||||
/**
|
||||
* CQRS : Command Query Responsibility Segregation. A pattern used to separate query services from commands or writes
|
||||
* services. The pattern is very simple but it has many consequences. For example, it can be used to tackle down a
|
||||
* complex domain, or to use other architectures that were hard to implement with the classical way.
|
||||
*
|
||||
* This implementation is an example of managing books and authors in a library. The persistence of books and authors is
|
||||
* done according to the CQRS architecture. A command side that deals with a data model to persist(insert,update,delete)
|
||||
* objects to a database. And a query side that uses native queries to get data from the database and return objects as
|
||||
* DTOs (Data transfer Objects).
|
||||
*
|
||||
*/
|
||||
public class App {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
|
||||
|
||||
/**
|
||||
* Program entry point
|
||||
*
|
||||
* @param args
|
||||
* command line args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
ICommandService commands = new CommandServiceImpl();
|
||||
|
||||
// Create Authors and Books using CommandService
|
||||
commands.authorCreated("eEvans", "Eric Evans", "eEvans@email.com");
|
||||
commands.authorCreated("jBloch", "Joshua Bloch", "jBloch@email.com");
|
||||
commands.authorCreated("mFowler", "Martin Fowler", "mFowler@email.com");
|
||||
|
||||
commands.bookAddedToAuthor("Domain-Driven Design", 60.08, "eEvans");
|
||||
commands.bookAddedToAuthor("Effective Java", 40.54, "jBloch");
|
||||
commands.bookAddedToAuthor("Java Puzzlers", 39.99, "jBloch");
|
||||
commands.bookAddedToAuthor("Java Concurrency in Practice", 29.40, "jBloch");
|
||||
commands.bookAddedToAuthor("Patterns of Enterprise Application Architecture", 54.01, "mFowler");
|
||||
commands.bookAddedToAuthor("Domain Specific Languages", 48.89, "mFowler");
|
||||
commands.authorNameUpdated("eEvans", "Eric J. Evans");
|
||||
|
||||
IQueryService queries = new QueryServiceImpl();
|
||||
|
||||
// Query the database using QueryService
|
||||
Author nullAuthor = queries.getAuthorByUsername("username");
|
||||
Author eEvans = queries.getAuthorByUsername("eEvans");
|
||||
BigInteger jBlochBooksCount = queries.getAuthorBooksCount("jBloch");
|
||||
BigInteger authorsCount = queries.getAuthorsCount();
|
||||
Book dddBook = queries.getBook("Domain-Driven Design");
|
||||
List<Book> jBlochBooks = queries.getAuthorBooks("jBloch");
|
||||
|
||||
LOGGER.info("Author username : {}", nullAuthor);
|
||||
LOGGER.info("Author eEvans : {}", eEvans);
|
||||
LOGGER.info("jBloch number of books : {}", jBlochBooksCount);
|
||||
LOGGER.info("Number of authors : {}", authorsCount);
|
||||
LOGGER.info("DDD book : {}", dddBook);
|
||||
LOGGER.info("jBloch books : {}", jBlochBooks);
|
||||
|
||||
HibernateUtil.getSessionFactory().close();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,145 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.commandes;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
|
||||
import com.iluwatar.cqrs.domain.model.Author;
|
||||
import com.iluwatar.cqrs.domain.model.Book;
|
||||
import com.iluwatar.cqrs.util.HibernateUtil;
|
||||
|
||||
/**
|
||||
* This class is an implementation of {@link ICommandService} interface. It uses Hibernate as an api for persistence.
|
||||
*
|
||||
*/
|
||||
public class CommandServiceImpl implements ICommandService {
|
||||
|
||||
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
|
||||
|
||||
private Author getAuthorByUsername(String username) {
|
||||
Author author = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
Query query = session.createQuery("from Author where username=:username");
|
||||
query.setParameter("username", username);
|
||||
author = (Author) query.uniqueResult();
|
||||
}
|
||||
if (author == null) {
|
||||
HibernateUtil.getSessionFactory().close();
|
||||
throw new NullPointerException("Author " + username + " doesn't exist!");
|
||||
}
|
||||
return author;
|
||||
}
|
||||
|
||||
private Book getBookByTitle(String title) {
|
||||
Book book = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
Query query = session.createQuery("from Book where title=:title");
|
||||
query.setParameter("title", title);
|
||||
book = (Book) query.uniqueResult();
|
||||
}
|
||||
if (book == null) {
|
||||
HibernateUtil.getSessionFactory().close();
|
||||
throw new NullPointerException("Book " + title + " doesn't exist!");
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void authorCreated(String username, String name, String email) {
|
||||
Author author = new Author(username, name, email);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.save(author);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bookAddedToAuthor(String title, double price, String username) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
Book book = new Book(title, price, author);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.save(book);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void authorNameUpdated(String username, String name) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
author.setName(name);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void authorUsernameUpdated(String oldUsername, String newUsername) {
|
||||
Author author = getAuthorByUsername(oldUsername);
|
||||
author.setUsername(newUsername);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void authorEmailUpdated(String username, String email) {
|
||||
Author author = getAuthorByUsername(username);
|
||||
author.setEmail(email);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(author);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bookTitleUpdated(String oldTitle, String newTitle) {
|
||||
Book book = getBookByTitle(oldTitle);
|
||||
book.setTitle(newTitle);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(book);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void bookPriceUpdated(String title, double price) {
|
||||
Book book = getBookByTitle(title);
|
||||
book.setPrice(price);
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
session.beginTransaction();
|
||||
session.update(book);
|
||||
session.getTransaction().commit();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.commandes;
|
||||
|
||||
/**
|
||||
* This interface represents the commands of the CQRS pattern
|
||||
*
|
||||
*/
|
||||
public interface ICommandService {
|
||||
|
||||
void authorCreated(String username, String name, String email);
|
||||
|
||||
void bookAddedToAuthor(String title, double price, String username);
|
||||
|
||||
void authorNameUpdated(String username, String name);
|
||||
|
||||
void authorUsernameUpdated(String oldUsername, String newUsername);
|
||||
|
||||
void authorEmailUpdated(String username, String email);
|
||||
|
||||
void bookTitleUpdated(String oldTitle, String newTitle);
|
||||
|
||||
void bookPriceUpdated(String title, double price);
|
||||
|
||||
}
|
100
cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Author.java
Normal file
@ -0,0 +1,100 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.domain.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
/**
|
||||
* This is an Author entity. It is used by Hibernate for persistence.
|
||||
*
|
||||
*/
|
||||
@Entity
|
||||
public class Author {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
private String username;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param username
|
||||
* username of the author
|
||||
* @param name
|
||||
* name of the author
|
||||
* @param email
|
||||
* email of the author
|
||||
*/
|
||||
public Author(String username, String name, String email) {
|
||||
super();
|
||||
this.username = username;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
protected Author() {
|
||||
super();
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Author [name=" + name + ", email=" + email + "]";
|
||||
}
|
||||
|
||||
}
|
102
cqrs/src/main/java/com/iluwatar/cqrs/domain/model/Book.java
Normal file
@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.domain.model;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.ManyToOne;
|
||||
|
||||
/**
|
||||
* This is a Book entity. It is used by Hibernate for persistence. Many books can be written by one {@link Author}
|
||||
*
|
||||
*/
|
||||
@Entity
|
||||
public class Book {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private long id;
|
||||
private String title;
|
||||
private double price;
|
||||
@ManyToOne
|
||||
private Author author;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param title
|
||||
* title of the book
|
||||
* @param price
|
||||
* price of the book
|
||||
* @param author
|
||||
* author of the book
|
||||
*/
|
||||
public Book(String title, double price, Author author) {
|
||||
super();
|
||||
this.title = title;
|
||||
this.price = price;
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
protected Book() {
|
||||
super();
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Author getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(Author author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Book [title=" + title + ", price=" + price + ", author=" + author + "]";
|
||||
}
|
||||
|
||||
}
|
93
cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java
Normal file
@ -0,0 +1,93 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.dto;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
*
|
||||
* This is a DTO (Data Transfer Object) author, contains only useful information to be returned
|
||||
*
|
||||
*/
|
||||
public class Author {
|
||||
|
||||
private String name;
|
||||
private String email;
|
||||
private String username;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* name of the author
|
||||
* @param email
|
||||
* email of the author
|
||||
* @param username
|
||||
* username of the author
|
||||
*/
|
||||
public Author(String name, String email, String username) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public Author() {
|
||||
super();
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "AuthorDTO [name=" + name + ", email=" + email + ", username=" + username + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(username, name, email);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof Author)) {
|
||||
return false;
|
||||
}
|
||||
Author other = (Author) obj;
|
||||
return username.equals(other.getUsername()) && email.equals(other.getEmail()) && name.equals(other.getName());
|
||||
|
||||
}
|
||||
|
||||
}
|
84
cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java
Normal file
@ -0,0 +1,84 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.dto;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
*
|
||||
* This is a DTO (Data Transfer Object) book, contains only useful information to be returned
|
||||
*
|
||||
*/
|
||||
public class Book {
|
||||
|
||||
private String title;
|
||||
private double price;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param title
|
||||
* title of the book
|
||||
* @param price
|
||||
* price of the book
|
||||
*/
|
||||
public Book(String title, double price) {
|
||||
super();
|
||||
this.title = title;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public Book() {
|
||||
super();
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "BookDTO [title=" + title + ", price=" + price + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(title, price);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof Book)) {
|
||||
return false;
|
||||
}
|
||||
Book book = (Book) obj;
|
||||
return title.equals(book.getTitle()) && price == book.getPrice();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.queries;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import com.iluwatar.cqrs.dto.Author;
|
||||
import com.iluwatar.cqrs.dto.Book;
|
||||
|
||||
/**
|
||||
*
|
||||
* This interface represents the query methods of the CQRS pattern
|
||||
*
|
||||
*/
|
||||
public interface IQueryService {
|
||||
|
||||
Author getAuthorByUsername(String username);
|
||||
|
||||
Book getBook(String title);
|
||||
|
||||
List<Book> getAuthorBooks(String username);
|
||||
|
||||
BigInteger getAuthorBooksCount(String username);
|
||||
|
||||
BigInteger getAuthorsCount();
|
||||
|
||||
}
|
@ -0,0 +1,105 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.queries;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.SQLQuery;
|
||||
import org.hibernate.Session;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.transform.Transformers;
|
||||
|
||||
import com.iluwatar.cqrs.dto.Author;
|
||||
import com.iluwatar.cqrs.dto.Book;
|
||||
import com.iluwatar.cqrs.util.HibernateUtil;
|
||||
|
||||
/**
|
||||
* This class is an implementation of {@link IQueryService}. It uses Hibernate native queries to return DTOs from the
|
||||
* database.
|
||||
*
|
||||
*/
|
||||
public class QueryServiceImpl implements IQueryService {
|
||||
|
||||
private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
|
||||
|
||||
@Override
|
||||
public Author getAuthorByUsername(String username) {
|
||||
Author authorDTo = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session
|
||||
.createSQLQuery("SELECT a.username as \"username\", a.name as \"name\", a.email as \"email\""
|
||||
+ "FROM Author a where a.username=:username");
|
||||
sqlQuery.setParameter("username", username);
|
||||
authorDTo = (Author) sqlQuery.setResultTransformer(Transformers.aliasToBean(Author.class)).uniqueResult();
|
||||
}
|
||||
return authorDTo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Book getBook(String title) {
|
||||
Book bookDTo = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session
|
||||
.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\"" + " FROM Book b where b.title=:title");
|
||||
sqlQuery.setParameter("title", title);
|
||||
bookDTo = (Book) sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).uniqueResult();
|
||||
}
|
||||
return bookDTo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Book> getAuthorBooks(String username) {
|
||||
List<Book> bookDTos = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT b.title as \"title\", b.price as \"price\""
|
||||
+ " FROM Author a , Book b where b.author_id = a.id and a.username=:username");
|
||||
sqlQuery.setParameter("username", username);
|
||||
bookDTos = sqlQuery.setResultTransformer(Transformers.aliasToBean(Book.class)).list();
|
||||
}
|
||||
return bookDTos;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigInteger getAuthorBooksCount(String username) {
|
||||
BigInteger bookcount = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery(
|
||||
"SELECT count(b.title)" + " FROM Book b, Author a where b.author_id = a.id and a.username=:username");
|
||||
sqlQuery.setParameter("username", username);
|
||||
bookcount = (BigInteger) sqlQuery.uniqueResult();
|
||||
}
|
||||
return bookcount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BigInteger getAuthorsCount() {
|
||||
BigInteger authorcount = null;
|
||||
try (Session session = sessionFactory.openSession()) {
|
||||
SQLQuery sqlQuery = session.createSQLQuery("SELECT count(id) from Author");
|
||||
authorcount = (BigInteger) sqlQuery.uniqueResult();
|
||||
}
|
||||
return authorcount;
|
||||
}
|
||||
|
||||
}
|
58
cqrs/src/main/java/com/iluwatar/cqrs/util/HibernateUtil.java
Normal file
@ -0,0 +1,58 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs.util;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistry;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* This class simply returns one instance of {@link SessionFactory} initialized when the application is started
|
||||
*
|
||||
*/
|
||||
public class HibernateUtil {
|
||||
|
||||
private static final SessionFactory SESSIONFACTORY = buildSessionFactory();
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
|
||||
|
||||
private static SessionFactory buildSessionFactory() {
|
||||
|
||||
// configures settings from hibernate.cfg.xml
|
||||
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
|
||||
try {
|
||||
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
|
||||
} catch (Exception ex) {
|
||||
StandardServiceRegistryBuilder.destroy(registry);
|
||||
LOGGER.error("Initial SessionFactory creation failed." + ex);
|
||||
throw new ExceptionInInitializerError(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory() {
|
||||
return SESSIONFACTORY;
|
||||
}
|
||||
|
||||
}
|
39
cqrs/src/main/resources/hibernate.cfg.xml
Normal file
@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014 Ilkka Seppälä
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-->
|
||||
<!DOCTYPE hibernate-configuration SYSTEM
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
|
||||
<property name="connection.driver_class">org.h2.Driver</property>
|
||||
<property name="connection.url">jdbc:h2:mem:test</property>
|
||||
<property name="connection.username">sa</property>
|
||||
<property name="hbm2ddl.auto">create</property>
|
||||
<mapping class="com.iluwatar.cqrs.domain.model.Author" />
|
||||
<mapping class="com.iluwatar.cqrs.domain.model.Book" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
37
cqrs/src/main/resources/logback.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014 Ilkka Seppälä
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-->
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
120
cqrs/src/test/java/com/iluwatar/cqrs/IntegrationTest.java
Normal file
@ -0,0 +1,120 @@
|
||||
/**
|
||||
* The MIT License
|
||||
* Copyright (c) 2014 Ilkka Seppälä
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
* THE SOFTWARE.
|
||||
*/
|
||||
package com.iluwatar.cqrs;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.iluwatar.cqrs.commandes.CommandServiceImpl;
|
||||
import com.iluwatar.cqrs.commandes.ICommandService;
|
||||
import com.iluwatar.cqrs.dto.Author;
|
||||
import com.iluwatar.cqrs.dto.Book;
|
||||
import com.iluwatar.cqrs.queries.IQueryService;
|
||||
import com.iluwatar.cqrs.queries.QueryServiceImpl;
|
||||
|
||||
/**
|
||||
* Integration test of IQueryService and ICommandService with h2 data
|
||||
*
|
||||
*/
|
||||
public class IntegrationTest {
|
||||
|
||||
private static IQueryService queryService;
|
||||
private static ICommandService commandService;
|
||||
|
||||
@BeforeClass
|
||||
public static void initialize() {
|
||||
commandService = new CommandServiceImpl();
|
||||
queryService = new QueryServiceImpl();
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void populateDatabase() {
|
||||
// create first author1
|
||||
commandService.authorCreated("username1", "name1", "email1");
|
||||
|
||||
// create author1 and update all its data
|
||||
commandService.authorCreated("username2", "name2", "email2");
|
||||
commandService.authorEmailUpdated("username2", "new_email2");
|
||||
commandService.authorNameUpdated("username2", "new_name2");
|
||||
commandService.authorUsernameUpdated("username2", "new_username2");
|
||||
|
||||
// add book1 to author1
|
||||
commandService.bookAddedToAuthor("title1", 10, "username1");
|
||||
|
||||
// add book2 to author1 and update all its data
|
||||
commandService.bookAddedToAuthor("title2", 20, "username1");
|
||||
commandService.bookPriceUpdated("title2", 30);
|
||||
commandService.bookTitleUpdated("title2", "new_title2");
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorByUsername() {
|
||||
Author author = queryService.getAuthorByUsername("username1");
|
||||
assertEquals("username1", author.getUsername());
|
||||
assertEquals("name1", author.getName());
|
||||
assertEquals("email1", author.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUpdatedAuthorByUsername() {
|
||||
Author author = queryService.getAuthorByUsername("new_username2");
|
||||
Author expectedAuthor = new Author("new_name2", "new_email2", "new_username2");
|
||||
assertEquals(expectedAuthor, author);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBook() {
|
||||
Book book = queryService.getBook("title1");
|
||||
assertEquals("title1", book.getTitle());
|
||||
assertEquals(10, book.getPrice(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorBooks() {
|
||||
List<Book> books = queryService.getAuthorBooks("username1");
|
||||
assertTrue(books.size() == 2);
|
||||
assertTrue(books.contains(new Book("title1", 10)));
|
||||
assertTrue(books.contains(new Book("new_title2", 30)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorBooksCount() {
|
||||
BigInteger bookCount = queryService.getAuthorBooksCount("username1");
|
||||
assertEquals(new BigInteger("2"), bookCount);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetAuthorsCount() {
|
||||
BigInteger authorCount = queryService.getAuthorsCount();
|
||||
assertEquals(new BigInteger("2"), authorCount);
|
||||
}
|
||||
|
||||
}
|
39
cqrs/src/test/resources/hibernate.cfg.xml
Normal file
@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014 Ilkka Seppälä
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-->
|
||||
<!DOCTYPE hibernate-configuration SYSTEM
|
||||
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
|
||||
<property name="connection.driver_class">org.h2.Driver</property>
|
||||
<property name="connection.url">jdbc:h2:mem:test</property>
|
||||
<property name="connection.username">sa</property>
|
||||
<property name="hbm2ddl.auto">create</property>
|
||||
<mapping class="com.iluwatar.cqrs.domain.model.Author" />
|
||||
<mapping class="com.iluwatar.cqrs.domain.model.Book" />
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
37
cqrs/src/test/resources/logback.xml
Normal file
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
|
||||
The MIT License
|
||||
Copyright (c) 2014 Ilkka Seppälä
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
-->
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="info">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|