diff --git a/.gitignore b/.gitignore index 64f833e2d..fd0bb7810 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,4 @@ datanucleus.log /bin/ *.log data-mapper/src/main/resources/log4j.xml +event-sourcing/Journal.json diff --git a/.travis.yml b/.travis.yml index 817b6635f..a2aaf764b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -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 \ No newline at end of file diff --git a/_scripts/postPumlsToServer.firstrun.output b/_scripts/postPumlsToServer.firstrun.output deleted file mode 100644 index ea77a49a5..000000000 --- a/_scripts/postPumlsToServer.firstrun.output +++ /dev/null @@ -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 diff --git a/abstract-factory/README.md b/abstract-factory/README.md index f153c1202..c049401fc 100644 --- a/abstract-factory/README.md +++ b/abstract-factory/README.md @@ -18,7 +18,107 @@ Kit Provide an interface for creating families of related or dependent objects without specifying their concrete classes. -![alt text](./etc/abstract-factory_1.png "Abstract Factory") +## 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) diff --git a/abstract-factory/etc/abstract-factory.png b/abstract-factory/etc/abstract-factory.png deleted file mode 100644 index c709276b6..000000000 Binary files a/abstract-factory/etc/abstract-factory.png and /dev/null differ diff --git a/abstract-factory/etc/abstract-factory.ucls b/abstract-factory/etc/abstract-factory.ucls deleted file mode 100644 index bdf1e1510..000000000 --- a/abstract-factory/etc/abstract-factory.ucls +++ /dev/null @@ -1,159 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/abstract-factory/etc/abstract-factory.urm.puml b/abstract-factory/etc/abstract-factory.urm.puml deleted file mode 100644 index 7b5e1b701..000000000 --- a/abstract-factory/etc/abstract-factory.urm.puml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/abstract-factory/etc/abstract-factory_1.png b/abstract-factory/etc/abstract-factory_1.png deleted file mode 100644 index 5990edd83..000000000 Binary files a/abstract-factory/etc/abstract-factory_1.png and /dev/null differ diff --git a/adapter/README.md b/adapter/README.md index 4059ea852..6de04a72c 100644 --- a/adapter/README.md +++ b/adapter/README.md @@ -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. -![alt text](./etc/adapter.png "Adapter") +## 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 diff --git a/adapter/etc/adapter.png b/adapter/etc/adapter.png deleted file mode 100644 index f43358b04..000000000 Binary files a/adapter/etc/adapter.png and /dev/null differ diff --git a/adapter/etc/adapter.ucls b/adapter/etc/adapter.ucls deleted file mode 100644 index 290ff544e..000000000 --- a/adapter/etc/adapter.ucls +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/adapter/etc/adapter.urm.puml b/adapter/etc/adapter.urm.puml deleted file mode 100644 index 847427a44..000000000 --- a/adapter/etc/adapter.urm.puml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/adapter/src/main/java/com/iluwatar/adapter/App.java b/adapter/src/main/java/com/iluwatar/adapter/App.java index 239424da9..a624cc38f 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/App.java +++ b/adapter/src/main/java/com/iluwatar/adapter/App.java @@ -34,14 +34,14 @@ package com.iluwatar.adapter; * object. This example uses the object adapter approach. * *

- * 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} ). * *

* The story of this implementation is this.
- * 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(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java deleted file mode 100644 index 5e4da91f8..000000000 --- a/adapter/src/main/java/com/iluwatar/adapter/BattleFishingBoat.java +++ /dev/null @@ -1,56 +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.adapter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - * Adapter class. Adapts the interface of the device ({@link FishingBoat}) into {@link BattleShip} - * interface expected by the client ({@link Captain}).
- * In this case we added a new function fire to suit the interface. We are reusing the - * {@link FishingBoat} without changing itself. The Adapter class can just map the functions of the - * Adaptee or add, delete features of the Adaptee. - * - */ -public class BattleFishingBoat implements BattleShip { - - private static final Logger LOGGER = LoggerFactory.getLogger(BattleFishingBoat.class); - - private FishingBoat boat; - - public BattleFishingBoat() { - boat = new FishingBoat(); - } - - @Override - public void fire() { - LOGGER.info("fire!"); - } - - @Override - public void move() { - boat.sail(); - } -} diff --git a/adapter/src/main/java/com/iluwatar/adapter/Captain.java b/adapter/src/main/java/com/iluwatar/adapter/Captain.java index 6d88b1975..369016980 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/Captain.java +++ b/adapter/src/main/java/com/iluwatar/adapter/Captain.java @@ -23,33 +23,26 @@ package com.iluwatar.adapter; /** - * The Captain uses {@link BattleShip} to fight.
+ * The Captain uses {@link RowingBoat} to sail.
* 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(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java index 2124d9d9f..c46814d18 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoat.java @@ -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"); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java similarity index 75% rename from bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java rename to adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java index 049133d91..1e758e917 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/MagicWeapon.java +++ b/adapter/src/main/java/com/iluwatar/adapter/FishingBoatAdapter.java @@ -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(); } } diff --git a/adapter/src/main/java/com/iluwatar/adapter/BattleShip.java b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java similarity index 92% rename from adapter/src/main/java/com/iluwatar/adapter/BattleShip.java rename to adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java index 62ee366e7..a9ca9ad39 100644 --- a/adapter/src/main/java/com/iluwatar/adapter/BattleShip.java +++ b/adapter/src/main/java/com/iluwatar/adapter/RowingBoat.java @@ -24,13 +24,11 @@ package com.iluwatar.adapter; /** * The interface expected by the client.
- * 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(); } diff --git a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java index 89c9bc5d5..9938f0559 100644 --- a/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java +++ b/adapter/src/test/java/com/iluwatar/adapter/AdapterPatternTest.java @@ -39,9 +39,9 @@ public class AdapterPatternTest { private Map 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(); } } diff --git a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java index f92792c39..d12ebbe19 100644 --- a/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java +++ b/async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/ThreadAsyncExecutor.java @@ -139,7 +139,7 @@ public class ThreadAsyncExecutor implements AsyncExecutor { @Override public void await() throws InterruptedException { synchronized (lock) { - if (!isCompleted()) { + while (!isCompleted()) { lock.wait(); } } diff --git a/balking/README.md b/balking/README.md index 1ca7ccfb1..f720c0d02 100644 --- a/balking/README.md +++ b/balking/README.md @@ -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 \ No newline at end of file diff --git a/bridge/README.md b/bridge/README.md index 6c1e70631..a37c35174 100644 --- a/bridge/README.md +++ b/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. -![alt text](./etc/bridge.png "Bridge") +## 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 diff --git a/bridge/etc/bridge.png b/bridge/etc/bridge.png deleted file mode 100644 index 00d3e611c..000000000 Binary files a/bridge/etc/bridge.png and /dev/null differ diff --git a/bridge/etc/bridge.ucls b/bridge/etc/bridge.ucls deleted file mode 100644 index 2eda6e1d1..000000000 --- a/bridge/etc/bridge.ucls +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/bridge/etc/bridge.urm.puml b/bridge/etc/bridge.urm.puml deleted file mode 100644 index 82e3b14af..000000000 --- a/bridge/etc/bridge.urm.puml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/bridge/src/main/java/com/iluwatar/bridge/App.java b/bridge/src/main/java/com/iluwatar/bridge/App.java index 4fc336042..c986de656 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/App.java +++ b/bridge/src/main/java/com/iluwatar/bridge/App.java @@ -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. *

- * 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. + *

+ * 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(); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java similarity index 90% rename from bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java rename to bridge/src/main/java/com/iluwatar/bridge/Enchantment.java index c7b47e780..dd0c17205 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeaponImpl.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Enchantment.java @@ -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(); } diff --git a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java similarity index 73% rename from bridge/src/main/java/com/iluwatar/bridge/Excalibur.java rename to bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java index ddd2ac540..8b12c6114 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Excalibur.java +++ b/bridge/src/main/java/com/iluwatar/bridge/FlyingEnchantment.java @@ -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."); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java similarity index 69% rename from bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java rename to bridge/src/main/java/com/iluwatar/bridge/Hammer.java index e70cbb96e..51bfda2a1 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Hammer.java @@ -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; } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java deleted file mode 100644 index b0d3070c1..000000000 --- a/bridge/src/main/java/com/iluwatar/bridge/MagicWeaponImpl.java +++ /dev/null @@ -1,38 +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; - -/** - * - * MagicWeaponImpl - * - */ -public abstract class MagicWeaponImpl { - - public abstract void wieldImp(); - - public abstract void swingImp(); - - public abstract void unwieldImp(); - -} diff --git a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java similarity index 76% rename from bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java rename to bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java index 0c7a6ce6b..8b08d155c 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Stormbringer.java +++ b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingEnchantment.java @@ -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."); } } diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java deleted file mode 100644 index 2ed27242a..000000000 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeaponImpl.java +++ /dev/null @@ -1,34 +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; - -/** - * - * SoulEatingMagicWeaponImpl - * - */ -public abstract class SoulEatingMagicWeaponImpl extends MagicWeaponImpl { - - public abstract void eatSoulImp(); - -} diff --git a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java b/bridge/src/main/java/com/iluwatar/bridge/Sword.java similarity index 69% rename from bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java rename to bridge/src/main/java/com/iluwatar/bridge/Sword.java index 927ac2d66..6f52943a6 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/SoulEatingMagicWeapon.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Sword.java @@ -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; } - } diff --git a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java similarity index 89% rename from bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java rename to bridge/src/main/java/com/iluwatar/bridge/Weapon.java index 0bd7d7b52..a2d21b88f 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/BlindingMagicWeaponImpl.java +++ b/bridge/src/main/java/com/iluwatar/bridge/Weapon.java @@ -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(); } diff --git a/bridge/src/test/java/com/iluwatar/bridge/FlyingMagicWeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java similarity index 70% rename from bridge/src/test/java/com/iluwatar/bridge/FlyingMagicWeaponTest.java rename to bridge/src/test/java/com/iluwatar/bridge/HammerTest.java index fca3ea9ab..a650bae04 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/FlyingMagicWeaponTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/HammerTest.java @@ -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); } - } \ No newline at end of file diff --git a/bridge/src/test/java/com/iluwatar/bridge/SoulEatingMagicWeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/SoulEatingMagicWeaponTest.java deleted file mode 100644 index b71fe2228..000000000 --- a/bridge/src/test/java/com/iluwatar/bridge/SoulEatingMagicWeaponTest.java +++ /dev/null @@ -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); - } - -} \ No newline at end of file diff --git a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java similarity index 69% rename from bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java rename to bridge/src/test/java/com/iluwatar/bridge/SwordTest.java index 85532d410..7ffd0e492 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/FlyingMagicWeapon.java +++ b/bridge/src/test/java/com/iluwatar/bridge/SwordTest.java @@ -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(); - } - -} +} \ No newline at end of file diff --git a/bridge/src/test/java/com/iluwatar/bridge/MagicWeaponTest.java b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java similarity index 67% rename from bridge/src/test/java/com/iluwatar/bridge/MagicWeaponTest.java rename to bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java index e883f03d3..daec1014a 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/MagicWeaponTest.java +++ b/bridge/src/test/java/com/iluwatar/bridge/WeaponTest.java @@ -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, times(1)).apply(); + verifyNoMoreInteractions(enchantment); weapon.wield(); - verify(weaponImpl, times(1)).wieldImp(); - verifyNoMoreInteractions(weaponImpl); + verify(enchantment, times(1)).onActivate(); + verifyNoMoreInteractions(enchantment); weapon.unwield(); - verify(weaponImpl, times(1)).unwieldImp(); - verifyNoMoreInteractions(weaponImpl); + verify(enchantment, times(1)).onDeactivate(); + verifyNoMoreInteractions(enchantment); } - } diff --git a/builder/README.md b/builder/README.md index 335862676..d255ec2f6 100644 --- a/builder/README.md +++ b/builder/README.md @@ -16,7 +16,103 @@ Separate the construction of a complex object from its representation so that the same construction process can create different representations. -![alt text](./etc/builder_1.png "Builder") +## 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 diff --git a/builder/etc/builder.png b/builder/etc/builder.png deleted file mode 100644 index a0280ba53..000000000 Binary files a/builder/etc/builder.png and /dev/null differ diff --git a/builder/etc/builder.ucls b/builder/etc/builder.ucls deleted file mode 100644 index 073c5cea7..000000000 --- a/builder/etc/builder.ucls +++ /dev/null @@ -1,162 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/builder/etc/builder.urm.puml b/builder/etc/builder.urm.puml deleted file mode 100644 index df8d73f36..000000000 --- a/builder/etc/builder.urm.puml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/builder/etc/builder_1.png b/builder/etc/builder_1.png deleted file mode 100644 index ec892c15f..000000000 Binary files a/builder/etc/builder_1.png and /dev/null differ diff --git a/composite/README.md b/composite/README.md index fce6ed6af..fbb21ecb3 100644 --- a/composite/README.md +++ b/composite/README.md @@ -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. -![alt text](./etc/composite_1.png "Composite") +## 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 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 letters) { + for (Letter l : letters) { + this.add(l); + } + } + @Override + protected void printThisBefore() { + System.out.print(" "); + } +} + +public class Sentence extends LetterComposite { + public Sentence(List 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 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 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 diff --git a/composite/etc/composite.png b/composite/etc/composite.png deleted file mode 100644 index 1e6e6258a..000000000 Binary files a/composite/etc/composite.png and /dev/null differ diff --git a/composite/etc/composite.ucls b/composite/etc/composite.ucls deleted file mode 100644 index 184c452f4..000000000 --- a/composite/etc/composite.ucls +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/composite/etc/composite.urm.puml b/composite/etc/composite.urm.puml deleted file mode 100644 index 82f2cab0d..000000000 --- a/composite/etc/composite.urm.puml +++ /dev/null @@ -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() - + add(letter : LetterComposite) - + count() : int - + print() - # printThisAfter() {abstract} - # printThisBefore() {abstract} - } - class Messenger { - + Messenger() - ~ messageFromElves() : LetterComposite - ~ messageFromOrcs() : LetterComposite - } - class Sentence { - + Sentence(words : List) - # printThisAfter() - # printThisBefore() - } - class Word { - + Word(letters : List) - # printThisAfter() - # printThisBefore() - } -} -LetterComposite --> "-children" LetterComposite -Letter --|> LetterComposite -Sentence --|> LetterComposite -Word --|> LetterComposite -@enduml \ No newline at end of file diff --git a/composite/etc/composite_1.png b/composite/etc/composite_1.png deleted file mode 100644 index 5f5b010dd..000000000 Binary files a/composite/etc/composite_1.png and /dev/null differ diff --git a/composite/src/main/java/com/iluwatar/composite/App.java b/composite/src/main/java/com/iluwatar/composite/App.java index 5d725c082..517920ac6 100644 --- a/composite/src/main/java/com/iluwatar/composite/App.java +++ b/composite/src/main/java/com/iluwatar/composite/App.java @@ -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(); diff --git a/composite/src/main/java/com/iluwatar/composite/Letter.java b/composite/src/main/java/com/iluwatar/composite/Letter.java index 036854f5d..cd149122d 100644 --- a/composite/src/main/java/com/iluwatar/composite/Letter.java +++ b/composite/src/main/java/com/iluwatar/composite/Letter.java @@ -39,9 +39,4 @@ public class Letter extends LetterComposite { protected void printThisBefore() { System.out.print(c); } - - @Override - protected void printThisAfter() { - // nop - } } diff --git a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java index c7c1344a0..f9ff68463 100644 --- a/composite/src/main/java/com/iluwatar/composite/LetterComposite.java +++ b/composite/src/main/java/com/iluwatar/composite/LetterComposite.java @@ -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 diff --git a/composite/src/main/java/com/iluwatar/composite/Sentence.java b/composite/src/main/java/com/iluwatar/composite/Sentence.java index e83406619..ae844cf59 100644 --- a/composite/src/main/java/com/iluwatar/composite/Sentence.java +++ b/composite/src/main/java/com/iluwatar/composite/Sentence.java @@ -40,11 +40,6 @@ public class Sentence extends LetterComposite { } } - @Override - protected void printThisBefore() { - // nop - } - @Override protected void printThisAfter() { System.out.print("."); diff --git a/composite/src/main/java/com/iluwatar/composite/Word.java b/composite/src/main/java/com/iluwatar/composite/Word.java index 1efc3465f..51e21a2d4 100644 --- a/composite/src/main/java/com/iluwatar/composite/Word.java +++ b/composite/src/main/java/com/iluwatar/composite/Word.java @@ -44,9 +44,4 @@ public class Word extends LetterComposite { protected void printThisBefore() { System.out.print(" "); } - - @Override - protected void printThisAfter() { - // nop - } } diff --git a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java index c5dc7da3f..6e93207cc 100644 --- a/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java +++ b/dao/src/main/java/com/iluwatar/dao/DbCustomerDao.java @@ -65,8 +65,8 @@ public class DbCustomerDao implements CustomerDao { Connection connection; try { connection = getConnection(); - PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); - ResultSet resultSet = statement.executeQuery(); + PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); //NOSONAR + ResultSet resultSet = statement.executeQuery(); //NOSONAR return StreamSupport.stream(new Spliterators.AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED) { @@ -82,7 +82,7 @@ public class DbCustomerDao implements CustomerDao { throw new RuntimeException(e); } } - }, false).onClose(() -> mutedClose(connection)); + }, false).onClose(() -> mutedClose(connection, statement, resultSet)); } catch (SQLException e) { throw new Exception(e.getMessage(), e); } @@ -92,8 +92,10 @@ public class DbCustomerDao implements CustomerDao { return dataSource.getConnection(); } - private void mutedClose(Connection connection) { + private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { try { + resultSet.close(); + statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); diff --git a/data-transfer-object/README.md b/data-transfer-object/README.md new file mode 100644 index 000000000..7fe2d9cdc --- /dev/null +++ b/data-transfer-object/README.md @@ -0,0 +1,31 @@ +--- +layout: pattern +title: Data Transfer Object +folder: data-transfer-object +permalink: /patterns/data-transfer-object/ +pumlid: RSh14SCW30NHLk82GFTq8uDYum71I5zn-t41kUtCswrfwL4bhBzEOFcRoFZEHyCPUxXOcGfHv387jHutWuqk_dAguktGj1WGKwV1_WJLvqWmLl-8fRbVKa22yXTosCWhHly1 +categories: Architectural +tags: + - Java + - KISS + - YAGNI + - Difficulty-Beginner +--- + +## Intent +Pass data with multiple attributes in one shot from client to server, +to avoid multiple calls to remote server. + +![alt text](./etc/data-transfer-object.urm.png "data-transfer-object") + +## Applicability +Use the Data Transfer Object pattern when + +* The client is asking for multiple information. And the information is related. +* When you want to boost the performance to get resources. +* You want reduced number of remote calls. + +## Credits + +* [Design Pattern - Transfer Object Pattern](https://www.tutorialspoint.com/design_pattern/transfer_object_pattern.htm) +* [Data Transfer Object](https://msdn.microsoft.com/en-us/library/ff649585.aspx) diff --git a/data-transfer-object/etc/data-transfer-object.ucls b/data-transfer-object/etc/data-transfer-object.ucls new file mode 100644 index 000000000..15f777aad --- /dev/null +++ b/data-transfer-object/etc/data-transfer-object.ucls @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/data-transfer-object/etc/data-transfer-object.urm.png b/data-transfer-object/etc/data-transfer-object.urm.png new file mode 100644 index 000000000..46facff8d Binary files /dev/null and b/data-transfer-object/etc/data-transfer-object.urm.png differ diff --git a/data-transfer-object/etc/data-transfer-object.urm.puml b/data-transfer-object/etc/data-transfer-object.urm.puml new file mode 100644 index 000000000..2c21dd21c --- /dev/null +++ b/data-transfer-object/etc/data-transfer-object.urm.puml @@ -0,0 +1,26 @@ +@startuml +package com.iluwatar.datatransfer { + class CustomerClientApp { + + CustomerClientApp() + + main(args : String[]) {static} + - printCustomerDetails(allCustomers : List) {static} + } + class CustomerDto { + - firstName : String + - id : String + - lastName : String + + CustomerDto(id : String, firstName : String, lastName : String) + + getFirstName() : String + + getId() : String + + getLastName() : String + } + class CustomerResource { + - customers : List + + CustomerResource(customers : List) + + delete(customerId : String) + + getAllCustomers() : List + + save(customer : CustomerDto) + } +} +CustomerResource --> "-customers" CustomerDto +@enduml \ No newline at end of file diff --git a/data-transfer-object/pom.xml b/data-transfer-object/pom.xml new file mode 100644 index 000000000..2f4871cb6 --- /dev/null +++ b/data-transfer-object/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.17.0-SNAPSHOT + + data-transfer-object + + + junit + junit + test + + + log4j + log4j + + + diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java new file mode 100644 index 000000000..f5fcebe03 --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerClientApp.java @@ -0,0 +1,84 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * 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.datatransfer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * The Data Transfer Object pattern is a design pattern in which an data transfer object is used to serve related + * information together to avoid multiple call for each piece of information. + *

+ * In this example, ({@link CustomerClientApp}) as as customer details consumer i.e. client to request for + * customer details to server. + *

+ * CustomerResource ({@link CustomerResource}) act as server to serve customer information. + * And The CustomerDto ({@link CustomerDto} is data transfer object to share customer information. + */ +public class CustomerClientApp { + + private static final Logger LOGGER = LoggerFactory.getLogger(CustomerClientApp.class); + + /** + * Method as act client and request to server for details. + * + * @param args program argument. + */ + public static void main(String[] args) { + List customers = new ArrayList<>(); + CustomerDto customerOne = new CustomerDto("1", "Kelly", "Brown"); + CustomerDto customerTwo = new CustomerDto("2", "Alfonso", "Bass"); + customers.add(customerOne); + customers.add(customerTwo); + + CustomerResource customerResource = new CustomerResource(customers); + + LOGGER.info("All customers:-"); + List allCustomers = customerResource.getAllCustomers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Deleting customer with id {1}"); + customerResource.delete(customerOne.getId()); + allCustomers = customerResource.getAllCustomers(); + printCustomerDetails(allCustomers); + + LOGGER.info("----------------------------------------------------------"); + + LOGGER.info("Adding customer three}"); + CustomerDto customerThree = new CustomerDto("3", "Lynda", "Blair"); + customerResource.save(customerThree); + allCustomers = customerResource.getAllCustomers(); + printCustomerDetails(allCustomers); + } + + private static void printCustomerDetails(List allCustomers) { + allCustomers.forEach(customer -> LOGGER.info(customer.getFirstName())); + } +} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java new file mode 100644 index 000000000..7dedf891c --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerDto.java @@ -0,0 +1,60 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * 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.datatransfer; + +/** + * {@link CustomerDto} is a data transfer object POJO. Instead of sending individual information to client + * We can send related information together in POJO. + *

+ * Dto will not have any business logic in it. + */ +public class CustomerDto { + private final String id; + private final String firstName; + private final String lastName; + + /** + * @param id customer id + * @param firstName customer first name + * @param lastName customer last name + */ + public CustomerDto(String id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public String getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } +} diff --git a/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java new file mode 100644 index 000000000..a4926d08c --- /dev/null +++ b/data-transfer-object/src/main/java/com/iluwatar/datatransfer/CustomerResource.java @@ -0,0 +1,63 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * 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.datatransfer; + +import java.util.List; + +/** + * The resource class which serves customer information. + * This class act as server in the demo. Which has all customer details. + */ +public class CustomerResource { + private List customers; + + /** + * @param customers initialize resource with existing customers. Act as database. + */ + public CustomerResource(List customers) { + this.customers = customers; + } + + /** + * @return : all customers in list. + */ + public List getAllCustomers() { + return customers; + } + + /** + * @param customer save new customer to list. + */ + public void save(CustomerDto customer) { + customers.add(customer); + } + + /** + * @param customerId delete customer with id {@code customerId} + */ + public void delete(String customerId) { + customers.removeIf(customer -> customer.getId().equals(customerId)); + } +} \ No newline at end of file diff --git a/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java new file mode 100644 index 000000000..adfe66b7d --- /dev/null +++ b/data-transfer-object/src/test/java/com/iluwatar/datatransfer/CustomerResourceTest.java @@ -0,0 +1,81 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2017 Gopinath Langote + * + * 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.datatransfer; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +/** + * tests {@link CustomerResource}. + */ +public class CustomerResourceTest { + @Test + public void shouldGetAllCustomers() { + CustomerDto customer = new CustomerDto("1", "Melody", "Yates"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + List allCustomers = customerResource.getAllCustomers(); + + assertEquals(allCustomers.size(), 1); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Melody"); + assertEquals(allCustomers.get(0).getLastName(), "Yates"); + } + + @Test + public void shouldSaveCustomer() { + CustomerDto customer = new CustomerDto("1", "Rita", "Reynolds"); + CustomerResource customerResource = new CustomerResource(new ArrayList<>()); + + customerResource.save(customer); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.get(0).getId(), "1"); + assertEquals(allCustomers.get(0).getFirstName(), "Rita"); + assertEquals(allCustomers.get(0).getLastName(), "Reynolds"); + } + + @Test + public void shouldDeleteCustomer() { + CustomerDto customer = new CustomerDto("1", "Terry", "Nguyen"); + List customers = new ArrayList<>(); + customers.add(customer); + + CustomerResource customerResource = new CustomerResource(customers); + + customerResource.delete(customer.getId()); + + List allCustomers = customerResource.getAllCustomers(); + assertEquals(allCustomers.size(), 0); + } + +} \ No newline at end of file diff --git a/decorator/README.md b/decorator/README.md index d2ba55afa..5f86166fe 100644 --- a/decorator/README.md +++ b/decorator/README.md @@ -19,7 +19,96 @@ Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. -![alt text](./etc/decorator.png "Decorator") +## Explanation + +Real world example + +> There is an angry troll living in the nearby hills. Usually it goes bare handed but sometimes it has a weapon. To arm the troll it's not necessary to create a new troll but to decorate it dynamically with a suitable weapon. + +In plain words + +> Decorator pattern lets you dynamically change the behavior of an object at run time by wrapping them in an object of a decorator class. + +Wikipedia says + +> In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern. + +**Programmatic Example** + +Lets take the troll example. First of all we have a simple troll implementing the troll interface + +``` +public interface Troll { + void attack(); + int getAttackPower(); + void fleeBattle(); +} + +public class SimpleTroll implements Troll { + + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTroll.class); + + @Override + public void attack() { + LOGGER.info("The troll tries to grab you!"); + } + + @Override + public int getAttackPower() { + return 10; + } + + @Override + public void fleeBattle() { + LOGGER.info("The troll shrieks in horror and runs away!"); + } +} +``` + +Next we want to add club for the troll. We can do it dynamically by using a decorator + +``` +public class ClubbedTroll implements Troll { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); + + private Troll decorated; + + public ClubbedTroll(Troll decorated) { + this.decorated = decorated; + } + + @Override + public void attack() { + decorated.attack(); + LOGGER.info("The troll swings at you with a club!"); + } + + @Override + public int getAttackPower() { + return decorated.getAttackPower() + 10; + } + + @Override + public void fleeBattle() { + decorated.fleeBattle(); + } +} +``` + +Here's the troll in action + +``` +// simple troll +Troll troll = new SimpleTroll(); +troll.attack(); // The troll tries to grab you! +troll.fleeBattle(); // The troll shrieks in horror and runs away! + +// change the behavior of the simple troll by adding a decorator +Troll clubbed = new ClubbedTroll(troll); +clubbed.attack(); // The troll tries to grab you! The troll swings at you with a club! +clubbed.fleeBattle(); // The troll shrieks in horror and runs away! +``` ## Applicability Use Decorator diff --git a/decorator/etc/decorator.png b/decorator/etc/decorator.png deleted file mode 100644 index 35a7ef35d..000000000 Binary files a/decorator/etc/decorator.png and /dev/null differ diff --git a/decorator/etc/decorator.ucls b/decorator/etc/decorator.ucls deleted file mode 100644 index 88bea6987..000000000 --- a/decorator/etc/decorator.ucls +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/decorator/etc/decorator.urm.puml b/decorator/etc/decorator.urm.puml deleted file mode 100644 index be878bd91..000000000 --- a/decorator/etc/decorator.urm.puml +++ /dev/null @@ -1,38 +0,0 @@ -@startuml -package com.iluwatar.decorator { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - class ClubbedTroll { - - LOGGER : Logger {static} - + ClubbedTroll(decorated : Troll) - + attack() - + getAttackPower() : int - } - class SimpleTroll { - - LOGGER : Logger {static} - + SimpleTroll() - + attack() - + fleeBattle() - + getAttackPower() : int - } - interface Troll { - + attack() {abstract} - + fleeBattle() {abstract} - + getAttackPower() : int {abstract} - } - class TrollDecorator { - - decorated : Troll - + TrollDecorator(decorated : Troll) - + attack() - + fleeBattle() - + getAttackPower() : int - } -} -TrollDecorator --> "-decorated" Troll -ClubbedTroll --|> TrollDecorator -SimpleTroll ..|> Troll -TrollDecorator ..|> Troll -@enduml \ No newline at end of file diff --git a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java index e309f17cd..edaa334a5 100644 --- a/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java +++ b/decorator/src/main/java/com/iluwatar/decorator/ClubbedTroll.java @@ -28,22 +28,29 @@ import org.slf4j.LoggerFactory; /** * Decorator that adds a club for the troll */ -public class ClubbedTroll extends TrollDecorator { +public class ClubbedTroll implements Troll { private static final Logger LOGGER = LoggerFactory.getLogger(ClubbedTroll.class); + private Troll decorated; + public ClubbedTroll(Troll decorated) { - super(decorated); + this.decorated = decorated; } @Override public void attack() { - super.attack(); + decorated.attack(); LOGGER.info("The troll swings at you with a club!"); } @Override public int getAttackPower() { - return super.getAttackPower() + 10; + return decorated.getAttackPower() + 10; + } + + @Override + public void fleeBattle() { + decorated.fleeBattle(); } } diff --git a/decorator/src/main/java/com/iluwatar/decorator/TrollDecorator.java b/decorator/src/main/java/com/iluwatar/decorator/TrollDecorator.java deleted file mode 100644 index d84c3a2b3..000000000 --- a/decorator/src/main/java/com/iluwatar/decorator/TrollDecorator.java +++ /dev/null @@ -1,53 +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.decorator; - -/** - * TrollDecorator is a decorator for {@link Troll} objects. The calls to the {@link Troll} interface - * are intercepted and decorated. Finally the calls are delegated to the decorated {@link Troll} - * object. - * - */ -public class TrollDecorator implements Troll { - - private Troll decorated; - - public TrollDecorator(Troll decorated) { - this.decorated = decorated; - } - - @Override - public void attack() { - decorated.attack(); - } - - @Override - public int getAttackPower() { - return decorated.getAttackPower(); - } - - @Override - public void fleeBattle() { - decorated.fleeBattle(); - } -} diff --git a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java index a097752cd..fb86615c6 100644 --- a/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java +++ b/decorator/src/test/java/com/iluwatar/decorator/ClubbedTrollTest.java @@ -34,7 +34,7 @@ import static org.mockito.internal.verification.VerificationModeFactory.times; public class ClubbedTrollTest { @Test - public void testSmartHostile() throws Exception { + public void testClubbedTroll() throws Exception { // Create a normal troll first, but make sure we can spy on it later on. final Troll simpleTroll = spy(new SimpleTroll()); diff --git a/event-queue/README.md b/event-queue/README.md index 35fdac45c..081c01449 100644 --- a/event-queue/README.md +++ b/event-queue/README.md @@ -11,7 +11,7 @@ tags: --- ## Intent -Event Queue is a good pattern if You have a limited accesibility resource (for example: +Event Queue is a good pattern if You have a limited accessibility resource (for example: Audio or Database), but You need to handle all the requests that want to use that. It puts all the requests in a queue and process them asynchronously. Gives the resource for the event when it is the next in the queue and in same time @@ -22,7 +22,7 @@ removes it from the queue. ## Applicability Use the Event Queue pattern when -* You have a limited accesibility resource and the asynchronous process is acceptable to reach that +* You have a limited accessibility resource and the asynchronous process is acceptable to reach that ## Credits diff --git a/event-sourcing/README.md b/event-sourcing/README.md new file mode 100644 index 000000000..1079405fa --- /dev/null +++ b/event-sourcing/README.md @@ -0,0 +1,33 @@ +--- +layout: pattern +title: Event Sourcing +folder: event-sourcing +permalink: /patterns/event-sourcing/ +categories: Architectural +tags: + - Java + - Difficulty Intermediate + - Performance +--- + +## Intent +Instead of storing just the current state of the data in a domain, use an append-only store to record the full series of actions taken on that data. The store acts as the system of record and can be used to materialize the domain objects. This can simplify tasks in complex domains, by avoiding the need to synchronize the data model and the business domain, while improving performance, scalability, and responsiveness. It can also provide consistency for transactional data, and maintain full audit trails and history that can enable compensating actions. + +![alt text](./etc/event-sourcing.png "Event Sourcing") + +## Applicability +Use the Event Sourcing pattern when + +* You need very high performance on persisting your application state even your application state have a complex relational data structure +* You need log of changes of your application state and ability to restore a state of any moment in time. +* You need to debug production problems by replaying the past events. + +## Real world examples + +* [The Lmax Architecture] (https://martinfowler.com/articles/lmax.html) + +## Credits + +* [Martin Fowler - Event Sourcing] (https://martinfowler.com/eaaDev/EventSourcing.html) +* [Event Sourcing | Microsoft Docs] (https://docs.microsoft.com/en-us/azure/architecture/patterns/event-sourcing) +* [Reference 3: Introducing Event Sourcing] (https://msdn.microsoft.com/en-us/library/jj591559.aspx) diff --git a/event-sourcing/etc/event-sourcing.png b/event-sourcing/etc/event-sourcing.png new file mode 100644 index 000000000..0b0098546 Binary files /dev/null and b/event-sourcing/etc/event-sourcing.png differ diff --git a/factory-method/etc/factory-method.ucls b/event-sourcing/etc/event-sourcing.ucls similarity index 51% rename from factory-method/etc/factory-method.ucls rename to event-sourcing/etc/event-sourcing.ucls index 562437995..2df56a479 100644 --- a/factory-method/etc/factory-method.ucls +++ b/event-sourcing/etc/event-sourcing.ucls @@ -1,111 +1,117 @@ - - + - + - - - - - - - - - - - - - - - - + - - - - - - - - - - - - - - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - + + - - + + - + - - - - + + + + - - - - - - + + - + + - index : int + + JsonFileJournal() + + readNext() : DomainEvent + + reset() + + write(domainEvent : DomainEvent) + } +} +package com.iluwatar.event.sourcing.processor { + class DomainEventProcessor { + - precessorJournal : ProcessorJournal + + DomainEventProcessor() + + process(domainEvent : DomainEvent) + + recover() + + setPrecessorJournal(precessorJournal : ProcessorJournal) + } +} +package com.iluwatar.event.sourcing.service { + class AccountService { + - eventProcessor : EventProcessor + + AccountService(eventProcessor : EventProcessor) + + createAccount(accountNo : int, owner : String) + } + class MoneyTransactionService { + - eventProcessor : EventProcessor + + MoneyTransactionService(eventProcessor : EventProcessor) + + depositMoney(accountNo : int, money : BigDecimal) + + transferMoney(accountNoFrom : int, accountNoTo : int, money : BigDecimal) + + withdrawalMoney(accountNo : int, money : BigDecimal) + } + class SequenceIdGenerator { + - sequenceId : long {static} + + SequenceIdGenerator() + + nextSequenceId() : long {static} + } +} +package com.iluwatar.event.sourcing.event { + class AccountCreateEvent { + - accountNo : int + - owner : String + + AccountCreateEvent(sequenceId : long, createdTime : long, accountNo : int, owner : String) + + getAccountNo() : int + + getOwner() : String + + process() + } + class MoneyDepositEvent { + - accountNo : int + - money : BigDecimal + + MoneyDepositEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal) + + getAccountNo() : int + + getMoney() : BigDecimal + + process() + } + class MoneyTransferEvent { + - accountNoFrom : int + - accountNoTo : int + - money : BigDecimal + + MoneyTransferEvent(sequenceId : long, createdTime : long, money : BigDecimal, accountNoFrom : int, accountNoTo : int) + + getAccountNoFrom() : int + + getAccountNoTo() : int + + getMoney() : BigDecimal + + process() + } + class MoneyWithdrawalEvent { + - accountNo : int + - money : BigDecimal + + MoneyWithdrawalEvent(sequenceId : long, createdTime : long, accountNo : int, money : BigDecimal) + + getAccountNo() : int + + getMoney() : BigDecimal + + process() + } +} +package com.iluwatar.event.sourcing.gateway { + class AccountCreateContractSender { + + AccountCreateContractSender() + + sendContractInfo(account : Account) + } + class Gateways { + - accountCreateContractSender : AccountCreateContractSender {static} + - transactionLogger : TransactionLogger {static} + + Gateways() + + getAccountCreateContractSender() : AccountCreateContractSender {static} + + getTransactionLogger() : TransactionLogger {static} + } + class TransactionLogger { + + TransactionLogger() + + log(transaction : Transaction) + } +} +package com.iluwatar.event.sourcing.app { + class App { + + App() + + main(args : String[]) {static} + } +} +package com.iluwatar.event.sourcing.state { + class AccountAggregate { + - accounts : Map {static} + + AccountAggregate() + + getAccount(accountNo : int) : Account {static} + + putAccount(account : Account) {static} + + resetState() {static} + } +} +package com.iluwatar.event.sourcing.domain { + class Account { + - accountNo : int + - money : BigDecimal + - owner : String + - transactions : List + + Account(accountNo : int, owner : String) + + copy() : Account + - depositMoney(money : BigDecimal) : Transaction + + getAccountNo() : int + + getMoney() : BigDecimal + + getOwner() : String + + getTransactions() : List + - handleDeposit(money : BigDecimal, realTime : boolean) + + handleEvent(accountCreateEvent : AccountCreateEvent) + + handleEvent(moneyDepositEvent : MoneyDepositEvent) + + handleEvent(moneyWithdrawalEvent : MoneyWithdrawalEvent) + + handleTransferFromEvent(moneyTransferEvent : MoneyTransferEvent) + + handleTransferToEvent(moneyTransferEvent : MoneyTransferEvent) + - handleWithdrawal(money : BigDecimal, realTime : boolean) + + setMoney(money : BigDecimal) + + setTransactions(transactions : List) + + toString() : String + - withdrawMoney(money : BigDecimal) : Transaction + } + class Transaction { + - accountNo : int + - lastBalance : BigDecimal + - moneyIn : BigDecimal + - moneyOut : BigDecimal + + Transaction(accountNo : int, moneyIn : BigDecimal, moneyOut : BigDecimal, lastBalance : BigDecimal) + + getAccountNo() : int + + getLastBalance() : BigDecimal + + getMoneyIn() : BigDecimal + + getMoneyOut() : BigDecimal + + toString() : String + } +} +package com.iluwatar.event.sourcing.api { + abstract class DomainEvent { + - createdTime : long + - eventClassName : String + - realTime : boolean + - sequenceId : long + + DomainEvent(sequenceId : long, createdTime : long, eventClassName : String) + + getCreatedTime() : long + + getEventClassName() : String + + getSequenceId() : long + + isRealTime() : boolean + + process() {abstract} + + setRealTime(realTime : boolean) + } + interface EventProcessor { + + process(DomainEvent) {abstract} + + recover() {abstract} + + setPrecessorJournal(ProcessorJournal) {abstract} + } + interface ProcessorJournal { + + readNext() : DomainEvent {abstract} + + reset() {abstract} + + write(DomainEvent) {abstract} + } +} +Gateways --> "-accountCreateContractSender" AccountCreateContractSender +DomainEventProcessor --> "-precessorJournal" ProcessorJournal +Account --> "-transactions" Transaction +Gateways --> "-transactionLogger" TransactionLogger +AccountService --> "-eventProcessor" EventProcessor +MoneyTransactionService --> "-eventProcessor" EventProcessor +AccountCreateEvent --|> DomainEvent +MoneyDepositEvent --|> DomainEvent +MoneyTransferEvent --|> DomainEvent +MoneyWithdrawalEvent --|> DomainEvent +JsonFileJournal ..|> ProcessorJournal +DomainEventProcessor ..|> EventProcessor +@enduml \ No newline at end of file diff --git a/event-sourcing/pom.xml b/event-sourcing/pom.xml new file mode 100644 index 000000000..35d462cb1 --- /dev/null +++ b/event-sourcing/pom.xml @@ -0,0 +1,50 @@ + + + + 4.0.0 + + java-design-patterns + com.iluwatar + 1.17.0-SNAPSHOT + + event-sourcing + + + junit + junit + test + + + + com.google.code.gson + gson + 2.8.1 + + + + \ No newline at end of file diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java new file mode 100644 index 000000000..50e9b503e --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/app/App.java @@ -0,0 +1,115 @@ +/** + * 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.event.sourcing.app; + +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import com.iluwatar.event.sourcing.processor.DomainEventProcessor; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; +import java.util.Date; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Event Sourcing : Instead of storing just the current state of the data in a domain, use an + * append-only store to record the full series of actions taken on that data. The store acts as the + * system of record and can be used to materialize the domain objects. This can simplify tasks in + * complex domains, by avoiding the need to synchronize the data model and the business domain, + * while improving performance, scalability, and responsiveness. It can also provide consistency for + * transactional data, and maintain full audit trails and history that can enable compensating + * actions. + * + * This App class is an example usage of Event Sourcing pattern. As an example, two bank account is + * created, then some money deposit and transfer actions are taken so a new state of accounts is + * created. At that point, state is cleared in order to represent a system shot down. After the shot + * down, system state is recovered by re-creating the past events from event journal. Then state is + * printed so a user can view the last state is same with the state before system shot down. + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class App { + + private static final Logger LOGGER = LoggerFactory.getLogger(App.class); + /** + * The constant ACCOUNT OF DAENERYS. + */ + public static final int ACCOUNT_OF_DAENERYS = 1; + /** + * The constant ACCOUNT OF JON. + */ + public static final int ACCOUNT_OF_JON = 2; + + /** + * The entry point of application. + * + * @param args the input arguments + */ + public static void main(String[] args) { + + DomainEventProcessor eventProcessor = new DomainEventProcessor(); + + + LOGGER.info("Running the system first time............"); + eventProcessor.reset(); + + LOGGER.info("Creating th accounts............"); + + eventProcessor.process(new AccountCreateEvent( + 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + + eventProcessor.process(new AccountCreateEvent( + 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + + LOGGER.info("Do some money operations............"); + + eventProcessor.process(new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + + eventProcessor.process(new MoneyDepositEvent( + 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + + eventProcessor.process(new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, + ACCOUNT_OF_JON)); + + LOGGER.info("...............State:............"); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString()); + + LOGGER.info("At that point system had a shot down, state in memory is cleared............"); + AccountAggregate.resetState(); + + LOGGER.info("Recover the system by the events in journal file............"); + + eventProcessor = new DomainEventProcessor(); + eventProcessor.recover(); + + LOGGER.info("...............Recovered State:............"); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS).toString()); + LOGGER.info(AccountAggregate.getAccount(ACCOUNT_OF_JON).toString()); + } + + +} diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java new file mode 100644 index 000000000..d2e5f429b --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/domain/Account.java @@ -0,0 +1,186 @@ +/** + * 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.event.sourcing.domain; + +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This is the Account class that holds the account info, the account number, + * account owner name and money of the account. Account class also have the business logic of events + * that effects this account. + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class Account { + + private static final Logger LOGGER = LoggerFactory.getLogger(Account.class); + + private final int accountNo; + private final String owner; + private BigDecimal money; + + /** + * Instantiates a new Account. + * + * @param accountNo the account no + * @param owner the owner + */ + public Account(int accountNo, String owner) { + this.accountNo = accountNo; + this.owner = owner; + money = BigDecimal.ZERO; + } + + /** + * Gets account no. + * + * @return the account no + */ + public int getAccountNo() { + return accountNo; + } + + /** + * Gets owner. + * + * @return the owner + */ + public String getOwner() { + return owner; + } + + /** + * Gets money. + * + * @return the money + */ + public BigDecimal getMoney() { + return money; + } + + /** + * Sets money. + * + * @param money the money + */ + public void setMoney(BigDecimal money) { + this.money = money; + } + + + /** + * Copy account. + * + * @return the account + */ + public Account copy() { + Account account = new Account(accountNo, owner); + account.setMoney(money); + return account; + } + + @Override + public String toString() { + return "Account{" + + "accountNo=" + accountNo + + ", owner='" + owner + '\'' + + ", money=" + money + + '}'; + } + + private void depositMoney(BigDecimal money) { + this.money = this.money.add(money); + } + + private void withdrawMoney(BigDecimal money) { + this.money = this.money.subtract(money); + } + + private void handleDeposit(BigDecimal money, boolean realTime) { + depositMoney(money); + AccountAggregate.putAccount(this); + if (realTime) { + LOGGER.info("Some external api for only realtime execution could be called here."); + } + } + + private void handleWithdrawal(BigDecimal money, boolean realTime) { + if (this.money.compareTo(money) == -1) { + throw new RuntimeException("Insufficient Account Balance"); + } + + withdrawMoney(money); + AccountAggregate.putAccount(this); + if (realTime) { + LOGGER.info("Some external api for only realtime execution could be called here."); + } + } + + /** + * Handles the MoneyDepositEvent. + * + * @param moneyDepositEvent the money deposit event + */ + public void handleEvent(MoneyDepositEvent moneyDepositEvent) { + handleDeposit(moneyDepositEvent.getMoney(), moneyDepositEvent.isRealTime()); + } + + + /** + * Handles the AccountCreateEvent. + * + * @param accountCreateEvent the account create event + */ + public void handleEvent(AccountCreateEvent accountCreateEvent) { + AccountAggregate.putAccount(this); + if (accountCreateEvent.isRealTime()) { + LOGGER.info("Some external api for only realtime execution could be called here."); + } + } + + /** + * Handles transfer from account event. + * + * @param moneyTransferEvent the money transfer event + */ + public void handleTransferFromEvent(MoneyTransferEvent moneyTransferEvent) { + handleWithdrawal(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); + } + + /** + * Handles transfer to account event. + * + * @param moneyTransferEvent the money transfer event + */ + public void handleTransferToEvent(MoneyTransferEvent moneyTransferEvent) { + handleDeposit(moneyTransferEvent.getMoney(), moneyTransferEvent.isRealTime()); + } + + +} diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java new file mode 100644 index 000000000..c526396f3 --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/AccountCreateEvent.java @@ -0,0 +1,82 @@ +/** + * 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.event.sourcing.event; + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.state.AccountAggregate; + +/** + * This is the class that implements account create event. + * Holds the necessary info for an account create event. + * Implements the process function that finds the event related + * domain objects and calls the related domain object's handle event functions + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class AccountCreateEvent extends DomainEvent { + + private final int accountNo; + private final String owner; + + /** + * Instantiates a new Account create event. + * + * @param sequenceId the sequence id + * @param createdTime the created time + * @param accountNo the account no + * @param owner the owner + */ + public AccountCreateEvent(long sequenceId, long createdTime, int accountNo, String owner) { + super(sequenceId, createdTime, "AccountCreateEvent"); + this.accountNo = accountNo; + this.owner = owner; + } + + /** + * Gets account no. + * + * @return the account no + */ + public int getAccountNo() { + return accountNo; + } + + /** + * Gets owner. + * + * @return the owner + */ + public String getOwner() { + return owner; + } + + @Override + public void process() { + Account account = AccountAggregate.getAccount(accountNo); + if (account != null) { + throw new RuntimeException("Account already exists"); + } + account = new Account(accountNo, owner); + account.handleEvent(this); + } +} diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java new file mode 100644 index 000000000..fa6539a4f --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/DomainEvent.java @@ -0,0 +1,101 @@ +/** + * 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.event.sourcing.event; + +import java.io.Serializable; + +/** + * This is the base class for domain events. All events must extend this class. + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public abstract class DomainEvent implements Serializable { + + private final long sequenceId; + private final long createdTime; + private final String eventClassName; + private boolean realTime = true; + + /** + * Instantiates a new Domain event. + * + * @param sequenceId the sequence id + * @param createdTime the created time + * @param eventClassName the event class name + */ + public DomainEvent(long sequenceId, long createdTime, String eventClassName) { + this.sequenceId = sequenceId; + this.createdTime = createdTime; + this.eventClassName = eventClassName; + } + + /** + * Gets sequence id. + * + * @return the sequence id + */ + public long getSequenceId() { + return sequenceId; + } + + /** + * Gets created time. + * + * @return the created time + */ + public long getCreatedTime() { + return createdTime; + } + + /** + * Is real time boolean. + * + * @return the boolean + */ + public boolean isRealTime() { + return realTime; + } + + /** + * Sets real time. + * + * @param realTime the real time + */ + public void setRealTime(boolean realTime) { + this.realTime = realTime; + } + + /** + * Process. + */ + public abstract void process(); + + /** + * Gets event class name. + * + * @return the event class name + */ + public String getEventClassName() { + return eventClassName; + } +} diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java new file mode 100644 index 000000000..1629263a7 --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyDepositEvent.java @@ -0,0 +1,82 @@ +/** + * 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.event.sourcing.event; + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; + +/** + * This is the class that implements money deposit event. + * Holds the necessary info for a money deposit event. + * Implements the process function that finds the event related + * domain objects and calls the related domain object's handle event functions + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class MoneyDepositEvent extends DomainEvent { + + private final BigDecimal money; + private final int accountNo; + + /** + * Instantiates a new Money deposit event. + * + * @param sequenceId the sequence id + * @param createdTime the created time + * @param accountNo the account no + * @param money the money + */ + public MoneyDepositEvent(long sequenceId, long createdTime, int accountNo, BigDecimal money) { + super(sequenceId, createdTime, "MoneyDepositEvent"); + this.money = money; + this.accountNo = accountNo; + } + + /** + * Gets money. + * + * @return the money + */ + public BigDecimal getMoney() { + return money; + } + + /** + * Gets account no. + * + * @return the account no + */ + public int getAccountNo() { + return accountNo; + } + + @Override + public void process() { + Account account = AccountAggregate.getAccount(accountNo); + if (account == null) { + throw new RuntimeException("Account not found"); + } + account.handleEvent(this); + } +} diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java new file mode 100644 index 000000000..0307d3af7 --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/event/MoneyTransferEvent.java @@ -0,0 +1,101 @@ +/** + * 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.event.sourcing.event; + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; + +/** + * This is the class that implements money transfer event. + * Holds the necessary info for a money transfer event. + * Implements the process function that finds the event related + * domain objects and calls the related domain object's handle event functions + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class MoneyTransferEvent extends DomainEvent { + + private final BigDecimal money; + private final int accountNoFrom; + private final int accountNoTo; + + /** + * Instantiates a new Money transfer event. + * + * @param sequenceId the sequence id + * @param createdTime the created time + * @param money the money + * @param accountNoFrom the account no from + * @param accountNoTo the account no to + */ + public MoneyTransferEvent(long sequenceId, long createdTime, BigDecimal money, int accountNoFrom, + int accountNoTo) { + super(sequenceId, createdTime, "MoneyTransferEvent"); + this.money = money; + this.accountNoFrom = accountNoFrom; + this.accountNoTo = accountNoTo; + } + + /** + * Gets money. + * + * @return the money + */ + public BigDecimal getMoney() { + return money; + } + + /** + * Gets account no which the money comes from. + * + * @return the account no from + */ + public int getAccountNoFrom() { + return accountNoFrom; + } + + /** + * Gets account no which the money goes to. + * + * @return the account no to + */ + public int getAccountNoTo() { + return accountNoTo; + } + + @Override + public void process() { + Account accountFrom = AccountAggregate.getAccount(accountNoFrom); + if (accountFrom == null) { + throw new RuntimeException("Account not found " + accountNoFrom); + } + Account accountTo = AccountAggregate.getAccount(accountNoTo); + if (accountTo == null) { + throw new RuntimeException("Account not found" + accountTo); + } + + accountFrom.handleTransferFromEvent(this); + accountTo.handleTransferToEvent(this); + } +} diff --git a/bridge/src/test/java/com/iluwatar/bridge/BlindingMagicWeaponTest.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java similarity index 53% rename from bridge/src/test/java/com/iluwatar/bridge/BlindingMagicWeaponTest.java rename to event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java index 97298a161..05308c7c1 100644 --- a/bridge/src/test/java/com/iluwatar/bridge/BlindingMagicWeaponTest.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/DomainEventProcessor.java @@ -1,6 +1,6 @@ /** * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * 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 @@ -20,36 +20,50 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.bridge; +package com.iluwatar.event.sourcing.processor; -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; +import com.iluwatar.event.sourcing.event.DomainEvent; /** - * Date: 12/6/15 - 11:15 PM + * This is the implementation of event processor. + * All events are processed by this class. + * This processor uses processorJournal to persist and recover events. * - * @author Jeroen Meulemeester + * Created by Serdar Hamzaogullari on 06.08.2017. */ -public class BlindingMagicWeaponTest extends MagicWeaponTest { +public class DomainEventProcessor { + + private final JsonFileJournal processorJournal = new JsonFileJournal(); /** - * Invoke all possible actions on the weapon and check if the actions are executed on the actual - * underlying weapon implementation. + * Process. + * + * @param domainEvent the domain event */ - @Test - public void testExcalibur() throws Exception { - final Excalibur excalibur = spy(new Excalibur()); - final BlindingMagicWeapon blindingMagicWeapon = new BlindingMagicWeapon(excalibur); - - testBasicWeaponActions(blindingMagicWeapon, excalibur); - - blindingMagicWeapon.blind(); - verify(excalibur, times(1)).blindImp(); - verifyNoMoreInteractions(excalibur); + public void process(DomainEvent domainEvent) { + domainEvent.process(); + processorJournal.write(domainEvent); } + /** + * Reset. + */ + public void reset() { + processorJournal.reset(); + } + + /** + * Recover. + */ + public void recover() { + DomainEvent domainEvent; + while (true) { + domainEvent = processorJournal.readNext(); + if (domainEvent == null) { + break; + } else { + domainEvent.process(); + } + } + } } diff --git a/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java new file mode 100644 index 000000000..870d8d00f --- /dev/null +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/processor/JsonFileJournal.java @@ -0,0 +1,144 @@ +/** + * 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.event.sourcing.processor; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.DomainEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; + +/** + * This is the implementation of event journal. + * This implementation serialize/deserialize the events with JSON + * and writes/reads them on a Journal.json file at the working directory. + * + * Created by Serdar Hamzaogullari on 06.08.2017. + */ +public class JsonFileJournal { + + private final File aFile; + private final List events = new ArrayList<>(); + private int index = 0; + + /** + * Instantiates a new Json file journal. + */ + public JsonFileJournal() { + aFile = new File("Journal.json"); + if (aFile.exists()) { + try (BufferedReader input = new BufferedReader( + new InputStreamReader(new FileInputStream(aFile), "UTF-8"))) { + String line; + while ((line = input.readLine()) != null) { + events.add(line); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } else { + reset(); + } + } + + + /** + * Write. + * + * @param domainEvent the domain event + */ + public void write(DomainEvent domainEvent) { + Gson gson = new Gson(); + JsonElement jsonElement; + if (domainEvent instanceof AccountCreateEvent) { + jsonElement = gson.toJsonTree(domainEvent, AccountCreateEvent.class); + } else if (domainEvent instanceof MoneyDepositEvent) { + jsonElement = gson.toJsonTree(domainEvent, MoneyDepositEvent.class); + } else if (domainEvent instanceof MoneyTransferEvent) { + jsonElement = gson.toJsonTree(domainEvent, MoneyTransferEvent.class); + } else { + throw new RuntimeException("Journal Event not recegnized"); + } + + try (Writer output = new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(aFile, true), "UTF-8"))) { + String eventString = jsonElement.toString(); + output.write(eventString + "\r\n"); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + + /** + * Reset. + */ + public void reset() { + aFile.delete(); + } + + + /** + * Read next domain event. + * + * @return the domain event + */ + public DomainEvent readNext() { + if (index >= events.size()) { + return null; + } + String event = events.get(index); + index++; + + JsonParser parser = new JsonParser(); + JsonElement jsonElement = parser.parse(event); + String eventClassName = jsonElement.getAsJsonObject().get("eventClassName").getAsString(); + Gson gson = new Gson(); + DomainEvent domainEvent; + if (eventClassName.equals("AccountCreateEvent")) { + domainEvent = gson.fromJson(jsonElement, AccountCreateEvent.class); + } else if (eventClassName.equals("MoneyDepositEvent")) { + domainEvent = gson.fromJson(jsonElement, MoneyDepositEvent.class); + } else if (eventClassName.equals("MoneyTransferEvent")) { + domainEvent = gson.fromJson(jsonElement, MoneyTransferEvent.class); + } else { + throw new RuntimeException("Journal Event not recegnized"); + } + + domainEvent.setRealTime(false); + return domainEvent; + } +} diff --git a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java similarity index 52% rename from bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java rename to event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java index 7cec530eb..2d957268e 100644 --- a/bridge/src/main/java/com/iluwatar/bridge/Mjollnir.java +++ b/event-sourcing/src/main/java/com/iluwatar/event/sourcing/state/AccountAggregate.java @@ -1,6 +1,6 @@ /** * The MIT License - * Copyright (c) 2014-2016 Ilkka Seppälä + * 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 @@ -20,37 +20,52 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package com.iluwatar.bridge; +package com.iluwatar.event.sourcing.state; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import com.iluwatar.event.sourcing.domain.Account; +import java.util.HashMap; +import java.util.Map; /** - * - * Mjollnir + * This is the static accounts map holder class. + * This class holds the state of the accounts. * + * Created by Serdar Hamzaogullari on 06.08.2017. */ -public class Mjollnir extends FlyingMagicWeaponImpl { +public class AccountAggregate { - private static final Logger LOGGER = LoggerFactory.getLogger(Mjollnir.class); + private static Map accounts = new HashMap<>(); - @Override - public void wieldImp() { - LOGGER.info("wielding Mjollnir"); + private AccountAggregate() { } - @Override - public void swingImp() { - LOGGER.info("swinging Mjollnir"); + /** + * Put account. + * + * @param account the account + */ + public static void putAccount(Account account) { + accounts.put(account.getAccountNo(), account); } - @Override - public void unwieldImp() { - LOGGER.info("unwielding Mjollnir"); + /** + * Gets account. + * + * @param accountNo the account no + * @return the copy of the account or null if not found + */ + public static Account getAccount(int accountNo) { + Account account = accounts.get(accountNo); + if (account == null) { + return null; + } + return account.copy(); } - @Override - public void flyImp() { - LOGGER.info("Mjollnir hits the enemy in the air and returns back to the owner's hand"); + /** + * Reset state. + */ + public static void resetState() { + accounts = new HashMap<>(); } } diff --git a/event-sourcing/src/test/java/IntegrationTest.java b/event-sourcing/src/test/java/IntegrationTest.java new file mode 100644 index 000000000..5a3f5718a --- /dev/null +++ b/event-sourcing/src/test/java/IntegrationTest.java @@ -0,0 +1,99 @@ +/** + * 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. + */ + +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_DAENERYS; +import static com.iluwatar.event.sourcing.app.App.ACCOUNT_OF_JON; + +import com.iluwatar.event.sourcing.domain.Account; +import com.iluwatar.event.sourcing.event.AccountCreateEvent; +import com.iluwatar.event.sourcing.event.MoneyDepositEvent; +import com.iluwatar.event.sourcing.event.MoneyTransferEvent; +import com.iluwatar.event.sourcing.processor.DomainEventProcessor; +import com.iluwatar.event.sourcing.state.AccountAggregate; +import java.math.BigDecimal; +import java.util.Date; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * Intergartion Test for Event Sourcing state recovery + * + * Created by Serdar Hamzaogullari on 19.08.2017. + */ +public class IntegrationTest { + + /** + * The Domain event processor. + */ + private DomainEventProcessor eventProcessor; + + /** + * Initialize. + */ + @Before + public void initialize() { + eventProcessor = new DomainEventProcessor(); + } + + /** + * Test state recovery. + */ + @Test + public void testStateRecovery() { + eventProcessor.reset(); + + eventProcessor.process(new AccountCreateEvent( + 0, new Date().getTime(), ACCOUNT_OF_DAENERYS, "Daenerys Targaryen")); + + eventProcessor.process(new AccountCreateEvent( + 1, new Date().getTime(), ACCOUNT_OF_JON, "Jon Snow")); + + eventProcessor.process(new MoneyDepositEvent( + 2, new Date().getTime(), ACCOUNT_OF_DAENERYS, new BigDecimal("100000"))); + + eventProcessor.process(new MoneyDepositEvent( + 3, new Date().getTime(), ACCOUNT_OF_JON, new BigDecimal("100"))); + + eventProcessor.process(new MoneyTransferEvent( + 4, new Date().getTime(), new BigDecimal("10000"), ACCOUNT_OF_DAENERYS, + ACCOUNT_OF_JON)); + + Account accountOfDaenerysBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonBeforeShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + AccountAggregate.resetState(); + + eventProcessor = new DomainEventProcessor(); + eventProcessor.recover(); + + Account accountOfDaenerysAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_DAENERYS); + Account accountOfJonAfterShotDown = AccountAggregate.getAccount(ACCOUNT_OF_JON); + + Assert.assertEquals(accountOfDaenerysBeforeShotDown.getMoney(), + accountOfDaenerysAfterShotDown.getMoney()); + Assert + .assertEquals(accountOfJonBeforeShotDown.getMoney(), accountOfJonAfterShotDown.getMoney()); + } + +} \ No newline at end of file diff --git a/factory-method/README.md b/factory-method/README.md index 17e0818e9..07c92d0e5 100644 --- a/factory-method/README.md +++ b/factory-method/README.md @@ -19,7 +19,49 @@ Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. -![alt text](./etc/factory-method_1.png "Factory Method") +## Explanation +Real world example + +> Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons. Depending on the customer at hand the right type of blacksmith is summoned. + +In plain words + +> It provides a way to delegate the instantiation logic to child classes. + +Wikipedia says + +> In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor. + + **Programmatic Example** + +Taking our blacksmith example above. First of all we have a blacksmith interface and some implementations for it + +``` +public interface Blacksmith { + Weapon manufactureWeapon(WeaponType weaponType); +} + +public class ElfBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return new ElfWeapon(weaponType); + } +} + +public class OrcBlacksmith implements Blacksmith { + public Weapon manufactureWeapon(WeaponType weaponType) { + return new OrcWeapon(weaponType); + } +} +``` + +Now as the customers come the correct type of blacksmith is summoned and requested weapons are manufactured + +``` +Blacksmith blacksmith = new ElfBlacksmith(); +blacksmith.manufactureWeapon(WeaponType.SPEAR); +blacksmith.manufactureWeapon(WeaponType.AXE); +// Elvish weapons are created +``` ## Applicability Use the Factory Method pattern when diff --git a/factory-method/etc/factory-method.png b/factory-method/etc/factory-method.png deleted file mode 100644 index c2edfd648..000000000 Binary files a/factory-method/etc/factory-method.png and /dev/null differ diff --git a/factory-method/etc/factory-method.urm.puml b/factory-method/etc/factory-method.urm.puml deleted file mode 100644 index 73a05e178..000000000 --- a/factory-method/etc/factory-method.urm.puml +++ /dev/null @@ -1,54 +0,0 @@ -@startuml -package com.iluwatar.factory.method { - class App { - - LOGGER : Logger {static} - - blacksmith : Blacksmith - + App(blacksmith : Blacksmith) - + main(args : String[]) {static} - - manufactureWeapons() - } - interface Blacksmith { - + manufactureWeapon(WeaponType) : Weapon {abstract} - } - class ElfBlacksmith { - + ElfBlacksmith() - + manufactureWeapon(weaponType : WeaponType) : Weapon - } - class ElfWeapon { - - weaponType : WeaponType - + ElfWeapon(weaponType : WeaponType) - + getWeaponType() : WeaponType - + toString() : String - } - class OrcBlacksmith { - + OrcBlacksmith() - + manufactureWeapon(weaponType : WeaponType) : Weapon - } - class OrcWeapon { - - weaponType : WeaponType - + OrcWeapon(weaponType : WeaponType) - + getWeaponType() : WeaponType - + toString() : String - } - interface Weapon { - + getWeaponType() : WeaponType {abstract} - } - enum WeaponType { - + AXE {static} - + SHORT_SWORD {static} - + SPEAR {static} - + UNDEFINED {static} - - title : String - + toString() : String - + valueOf(name : String) : WeaponType {static} - + values() : WeaponType[] {static} - } -} -ElfWeapon --> "-weaponType" WeaponType -OrcWeapon --> "-weaponType" WeaponType -App --> "-blacksmith" Blacksmith -ElfBlacksmith ..|> Blacksmith -ElfWeapon ..|> Weapon -OrcBlacksmith ..|> Blacksmith -OrcWeapon ..|> Weapon -@enduml \ No newline at end of file diff --git a/factory-method/etc/factory-method_1.png b/factory-method/etc/factory-method_1.png deleted file mode 100644 index 6b9276781..000000000 Binary files a/factory-method/etc/factory-method_1.png and /dev/null differ diff --git a/feature-toggle/README.md b/feature-toggle/README.md index 3bb91ad5a..06d956178 100644 --- a/feature-toggle/README.md +++ b/feature-toggle/README.md @@ -22,7 +22,7 @@ going to phase out is never removed, causing redundant code smells and increased ![alt text](./etc/feature-toggle.png "Feature Toggle") ## Applicability -Use the Feature Toogle pattern when +Use the Feature Toggle pattern when * Giving different features to different users. * Rolling out a new feature incrementally. diff --git a/layers/README.md b/layers/README.md index 8eac62412..62b562938 100644 --- a/layers/README.md +++ b/layers/README.md @@ -21,7 +21,7 @@ Layers is an architectural style where software responsibilities are ## Applicability Use the Layers architecture when -* you want clearly divide software responsibilities into differents parts of the program +* you want clearly divide software responsibilities into different parts of the program * you want to prevent a change from propagating throughout the application * you want to make your application more maintainable and testable diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java index 01af677ae..f5606e638 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileLoader.java @@ -25,6 +25,10 @@ package com.iluwatar.model.view.presenter; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; +import java.io.Serializable; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Every instance of this class represents the Model component in the Model-View-Presenter @@ -32,7 +36,14 @@ import java.io.FileReader; *

* It is responsible for reading and loading the contents of a given file. */ -public class FileLoader { +public class FileLoader implements Serializable{ + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = -4745803872902019069L; + + private static final Logger LOGGER = LoggerFactory.getLogger(FileLoader.class); /** * Indicates if the file is loaded or not. @@ -48,7 +59,8 @@ public class FileLoader { * Loads the data of the file specified. */ public String loadData() { - try (BufferedReader br = new BufferedReader(new FileReader(new File(this.fileName)))) { + String dataFileName = this.fileName; + try (BufferedReader br = new BufferedReader(new FileReader(new File(dataFileName)))) { StringBuilder sb = new StringBuilder(); String line; @@ -60,7 +72,7 @@ public class FileLoader { return sb.toString(); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("File {} does not exist", dataFileName); } return null; diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java index f2fefe8eb..560a8d274 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorPresenter.java @@ -22,13 +22,20 @@ */ package com.iluwatar.model.view.presenter; +import java.io.Serializable; + /** * Every instance of this class represents the Presenter component in the Model-View-Presenter * architectural pattern. *

* It is responsible for reacting to the user's actions and update the View component. */ -public class FileSelectorPresenter { +public class FileSelectorPresenter implements Serializable{ + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 1210314339075855074L; /** * The View component that the presenter interacts with. diff --git a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java index cfafadbab..5272ea0b7 100644 --- a/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java +++ b/model-view-presenter/src/main/java/com/iluwatar/model/view/presenter/FileSelectorView.java @@ -22,11 +22,13 @@ */ package com.iluwatar.model.view.presenter; +import java.io.Serializable; + /** * This interface represents the View component in the Model-View-Presenter pattern. It can be * implemented by either the GUI components, or by the Stub. */ -public interface FileSelectorView { +public interface FileSelectorView extends Serializable{ /** * Opens the view. diff --git a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java index df6e887b8..e76d00352 100644 --- a/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java +++ b/object-pool/src/main/java/com/iluwatar/object/pool/ObjectPool.java @@ -55,7 +55,7 @@ public abstract class ObjectPool { } @Override - public String toString() { + public synchronized String toString() { return String.format("Pool available=%d inUse=%d", available.size(), inUse.size()); } } diff --git a/pom.xml b/pom.xml index 4f4b5dee6..44461b091 100644 --- a/pom.xml +++ b/pom.xml @@ -143,7 +143,8 @@ extension-objects marker cqrs - + event-sourcing + data-transfer-object @@ -460,6 +461,15 @@ java-design-patterns + singleton + factory-method + abstract-factory + builder + prototype + adapter + bridge + composite + decorator diff --git a/promise/README.md b/promise/README.md index 65d463550..37fd214b7 100644 --- a/promise/README.md +++ b/promise/README.md @@ -27,7 +27,7 @@ in a synchronous way. Promise pattern is applicable in concurrent programming when some work needs to be done asynchronously and: -* code maintainablity and readability suffers due to callback hell. +* code maintainability and readability suffers due to callback hell. * you need to compose promises and need better error handling for asynchronous tasks. * you want to use functional style of programming. @@ -44,4 +44,4 @@ and: ## Credits * [You are missing the point to Promises](https://gist.github.com/domenic/3889970) -* [Functional style callbacks using CompleteableFuture](https://www.infoq.com/articles/Functional-Style-Callbacks-Using-CompletableFuture) +* [Functional style callbacks using CompletableFuture](https://www.infoq.com/articles/Functional-Style-Callbacks-Using-CompletableFuture) diff --git a/prototype/README.md b/prototype/README.md index fe9e17917..477cd6e6f 100644 --- a/prototype/README.md +++ b/prototype/README.md @@ -15,14 +15,57 @@ tags: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. -![alt text](./etc/prototype_1.png "Prototype") +## Explanation +Real world example + +> Remember Dolly? The sheep that was cloned! Lets not get into the details but the key point here is that it is all about cloning. + +In plain words + +> Create object based on an existing object through cloning. + +Wikipedia says + +> The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. + +In short, it allows you to create a copy of an existing object and modify it to your needs, instead of going through the trouble of creating an object from scratch and setting it up. + +**Programmatic Example** + +In Java, it can be easily done by implementing `Cloneable` and overriding `clone` from `Object` + +``` +class Sheep implements Cloneable { + private String name; + public Sheep(String name) { this.name = name; } + public void setName(String name) { this.name = name; } + public String getName() { return name; } + @Override + public Sheep clone() throws CloneNotSupportedException { + return new Sheep(name); + } +} +``` + +Then it can be cloned like below + +``` +Sheep original = new Sheep("Jolly"); +System.out.println(original.getName()); // Jolly + +// Clone and modify what is required +Sheep cloned = original.clone(); +cloned.setName("Dolly"); +System.out.println(cloned.getName()); // Dolly +``` ## Applicability Use the Prototype pattern when a system should be independent of how its products are created, composed and represented; and -* when the classes to instantiate are specified at run-time, for example, by dynamic loading; or -* to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or +* when the classes to instantiate are specified at run-time, for example, by dynamic loading +* to avoid building a class hierarchy of factories that parallels the class hierarchy of products * when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state +* when object creation is expensive compared to cloning ## Real world examples diff --git a/prototype/etc/prototype.png b/prototype/etc/prototype.png deleted file mode 100644 index 073b472e5..000000000 Binary files a/prototype/etc/prototype.png and /dev/null differ diff --git a/prototype/etc/prototype.ucls b/prototype/etc/prototype.ucls deleted file mode 100644 index 6d19fdc23..000000000 --- a/prototype/etc/prototype.ucls +++ /dev/null @@ -1,182 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/prototype/etc/prototype.urm.puml b/prototype/etc/prototype.urm.puml deleted file mode 100644 index 801679fb7..000000000 --- a/prototype/etc/prototype.urm.puml +++ /dev/null @@ -1,82 +0,0 @@ -@startuml -package com.iluwatar.prototype { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - abstract class Beast { - + Beast() - + clone() : Beast {abstract} - } - class ElfBeast { - + ElfBeast() - + clone() : Beast - + toString() : String - } - class ElfMage { - + ElfMage() - + clone() : Mage - + toString() : String - } - class ElfWarlord { - + ElfWarlord() - + clone() : Warlord - + toString() : String - } - interface HeroFactory { - + createBeast() : Beast {abstract} - + createMage() : Mage {abstract} - + createWarlord() : Warlord {abstract} - } - class HeroFactoryImpl { - - beast : Beast - - mage : Mage - - warlord : Warlord - + HeroFactoryImpl(mage : Mage, warlord : Warlord, beast : Beast) - + createBeast() : Beast - + createMage() : Mage - + createWarlord() : Warlord - } - abstract class Mage { - + Mage() - + clone() : Mage {abstract} - } - class OrcBeast { - + OrcBeast() - + clone() : Beast - + toString() : String - } - class OrcMage { - + OrcMage() - + clone() : Mage - + toString() : String - } - class OrcWarlord { - + OrcWarlord() - + clone() : Warlord - + toString() : String - } - abstract class Prototype { - + Prototype() - + clone() : Object {abstract} - } - abstract class Warlord { - + Warlord() - + clone() : Warlord {abstract} - } -} -HeroFactoryImpl --> "-beast" Beast -HeroFactoryImpl --> "-warlord" Warlord -HeroFactoryImpl --> "-mage" Mage -Beast --|> Prototype -ElfBeast --|> Beast -ElfMage --|> Mage -ElfWarlord --|> Warlord -HeroFactoryImpl ..|> HeroFactory -Mage --|> Prototype -OrcBeast --|> Beast -OrcMage --|> Mage -OrcWarlord --|> Warlord -Warlord --|> Prototype -@enduml \ No newline at end of file diff --git a/prototype/etc/prototype_1.png b/prototype/etc/prototype_1.png deleted file mode 100644 index 8b513c8d2..000000000 Binary files a/prototype/etc/prototype_1.png and /dev/null differ diff --git a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java index 4db4f5e2a..446628769 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java +++ b/reactor/src/main/java/com/iluwatar/reactor/app/AppClient.java @@ -65,6 +65,7 @@ public class AppClient { * @throws IOException if any I/O error occurs. */ public void start() throws IOException { + LOGGER.info("Starting logging clients"); service.execute(new TcpLoggingClient("Client 1", 6666)); service.execute(new TcpLoggingClient("Client 2", 6667)); service.execute(new UdpLoggingClient("Client 3", 6668)); @@ -81,16 +82,17 @@ public class AppClient { try { service.awaitTermination(1000, TimeUnit.SECONDS); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("exception awaiting termination", e); } } + LOGGER.info("Logging clients stopped"); } private static void artificialDelayOf(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("sleep interrupted", e); } } @@ -119,7 +121,7 @@ public class AppClient { PrintWriter writer = new PrintWriter(outputStream); sendLogRequests(writer, socket.getInputStream()); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("error sending requests", e); throw new RuntimeException(e); } } @@ -185,7 +187,7 @@ public class AppClient { artificialDelayOf(100); } } catch (IOException e1) { - e1.printStackTrace(); + LOGGER.error("error sending packets", e1); } } } diff --git a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java index bc5b27494..a315389a3 100644 --- a/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java +++ b/reactor/src/main/java/com/iluwatar/reactor/framework/NioReactor.java @@ -94,7 +94,7 @@ public class NioReactor { LOGGER.info("Reactor started, waiting for events..."); eventLoop(); } catch (IOException e) { - e.printStackTrace(); + LOGGER.error("exception in event loop", e); } }); } @@ -112,6 +112,7 @@ public class NioReactor { selector.wakeup(); reactorMain.awaitTermination(4, TimeUnit.SECONDS); selector.close(); + LOGGER.info("Reactor stopped"); } /** @@ -206,7 +207,7 @@ public class NioReactor { try { key.channel().close(); } catch (IOException e1) { - e1.printStackTrace(); + LOGGER.error("error closing channel", e1); } } } diff --git a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java index 413bbc017..7aa80f8cc 100644 --- a/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java +++ b/reactor/src/test/java/com/iluwatar/reactor/app/ReactorTest.java @@ -24,10 +24,13 @@ package com.iluwatar.reactor.app; import java.io.IOException; +import com.iluwatar.reactor.framework.NioReactor; import org.junit.Test; import com.iluwatar.reactor.framework.SameThreadDispatcher; import com.iluwatar.reactor.framework.ThreadPoolDispatcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @@ -36,6 +39,8 @@ import com.iluwatar.reactor.framework.ThreadPoolDispatcher; */ public class ReactorTest { + private static final Logger LOGGER = LoggerFactory.getLogger(ReactorTest.class); + /** * Test the application using pooled thread dispatcher. * @@ -44,6 +49,7 @@ public class ReactorTest { */ @Test public void testAppUsingThreadPoolDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingThreadPoolDispatcher start"); App app = new App(new ThreadPoolDispatcher(2)); app.start(); @@ -54,12 +60,13 @@ public class ReactorTest { try { Thread.sleep(2000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("sleep interrupted", e); } client.stop(); app.stop(); + LOGGER.info("testAppUsingThreadPoolDispatcher stop"); } /** @@ -70,6 +77,7 @@ public class ReactorTest { */ @Test public void testAppUsingSameThreadDispatcher() throws IOException, InterruptedException { + LOGGER.info("testAppUsingSameThreadDispatcher start"); App app = new App(new SameThreadDispatcher()); app.start(); @@ -80,11 +88,12 @@ public class ReactorTest { try { Thread.sleep(2000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("sleep interrupted", e); } client.stop(); app.stop(); + LOGGER.info("testAppUsingSameThreadDispatcher stop"); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java index af7b5df2c..42335f313 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/App.java @@ -23,14 +23,15 @@ package com.iluwatar.reader.writer.lock; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * * In a multiple thread applications, the threads may try to synchronize the shared resources @@ -62,21 +63,42 @@ public class App { ExecutorService executeService = Executors.newFixedThreadPool(10); ReaderWriterLock lock = new ReaderWriterLock(); - - // Start 5 readers + + // Start writers IntStream.range(0, 5) - .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock()))); + .forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock(), + ThreadLocalRandom.current().nextLong(5000)))); + LOGGER.info("Writers added..."); - // Start 5 writers + // Start readers IntStream.range(0, 5) - .forEach(i -> executeService.submit(new Writer("Writer " + i, lock.writeLock()))); + .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), + ThreadLocalRandom.current().nextLong(10)))); + LOGGER.info("Readers added..."); + + try { + Thread.sleep(5000L); + } catch (InterruptedException e) { + LOGGER.error("Error sleeping before adding more readers", e); + Thread.currentThread().interrupt(); + } + + // Start readers + IntStream.range(6, 10) + .forEach(i -> executeService.submit(new Reader("Reader " + i, lock.readLock(), + ThreadLocalRandom.current().nextLong(10)))); + LOGGER.info("More readers added..."); + + + // In the system console, it can see that the read operations are executed concurrently while // write operations are exclusive. executeService.shutdown(); try { executeService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { - LOGGER.error("Error waiting for ExecutorService shutdown"); + LOGGER.error("Error waiting for ExecutorService shutdown", e); + Thread.currentThread().interrupt(); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java index 006aff7d7..b0ccecaba 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Reader.java @@ -22,11 +22,11 @@ */ package com.iluwatar.reader.writer.lock; +import java.util.concurrent.locks.Lock; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.locks.Lock; - /** * Reader class, read when it acquired the read lock */ @@ -37,10 +37,30 @@ public class Reader implements Runnable { private Lock readLock; private String name; + + private long readingTime; - public Reader(String name, Lock readLock) { + /** + * Create new Reader + * + * @param name - Name of the thread owning the reader + * @param readLock - Lock for this reader + * @param readingTime - amount of time (in milliseconds) for this reader to engage reading + */ + public Reader(String name, Lock readLock, long readingTime) { this.name = name; this.readLock = readLock; + this.readingTime = readingTime; + } + + /** + * Create new Reader who reads for 250ms + * + * @param name - Name of the thread owning the reader + * @param readLock - Lock for this reader + */ + public Reader(String name, Lock readLock) { + this(name, readLock, 250L); } @Override @@ -49,7 +69,8 @@ public class Reader implements Runnable { try { read(); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.info("InterruptedException when reading", e); + Thread.currentThread().interrupt(); } finally { readLock.unlock(); } @@ -61,7 +82,7 @@ public class Reader implements Runnable { */ public void read() throws InterruptedException { LOGGER.info("{} begin", name); - Thread.sleep(250); - LOGGER.info("{} finish", name); + Thread.sleep(readingTime); + LOGGER.info("{} finish after reading {}ms", name, readingTime); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java index e7b3c4451..b377b2273 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/ReaderWriterLock.java @@ -29,13 +29,18 @@ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * Class responsible for control the access for reader or writer * - * Allows multiple readers to hold the lock at same time, but if any writer holds the lock then - * readers wait. If reader holds the lock then writer waits. This lock is not fair. + * Allows multiple readers to hold the lock at same time, but if any writer holds the lock then readers wait. If reader + * holds the lock then writer waits. This lock is not fair. */ public class ReaderWriterLock implements ReadWriteLock { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReaderWriterLock.class); private Object readerMutex = new Object(); @@ -45,10 +50,10 @@ public class ReaderWriterLock implements ReadWriteLock { /** * Global mutex is used to indicate that whether reader or writer gets the lock in the moment. *

- * 1. When it contains the reference of {@link readerLock}, it means that the lock is acquired by - * the reader, another reader can also do the read operation concurrently.
- * 2. When it contains the reference of reference of {@link writerLock}, it means that the lock is - * acquired by the writer exclusively, no more reader or writer can get the lock. + * 1. When it contains the reference of {@link readerLock}, it means that the lock is acquired by the reader, another + * reader can also do the read operation concurrently.
+ * 2. When it contains the reference of reference of {@link writerLock}, it means that the lock is acquired by the + * writer exclusively, no more reader or writer can get the lock. *

* This is the most important field in this class to control the access for reader/writer. */ @@ -74,13 +79,6 @@ public class ReaderWriterLock implements ReadWriteLock { return globalMutex.contains(writerLock); } - /** - * return true when globalMutex hold the reference of readerLock - */ - private boolean doesReaderOwnThisLock() { - return globalMutex.contains(readerLock); - } - /** * Nobody get the lock when globalMutex contains nothing * @@ -89,14 +87,6 @@ public class ReaderWriterLock implements ReadWriteLock { return globalMutex.isEmpty(); } - private static void waitUninterruptibly(Object o) { - try { - o.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - /** * Reader Lock, can be access for more than one reader concurrently if no writer get the lock */ @@ -104,31 +94,35 @@ public class ReaderWriterLock implements ReadWriteLock { @Override public void lock() { - synchronized (readerMutex) { - currentReaderCount++; if (currentReaderCount == 1) { - // Try to get the globalMutex lock for the first reader - synchronized (globalMutex) { - while (true) { - // If the no one get the lock or the lock is locked by reader, just set the reference - // to the globalMutex to indicate that the lock is locked by Reader. - if (isLockFree() || doesReaderOwnThisLock()) { - globalMutex.add(this); - break; - } else { - // If lock is acquired by the write, let the thread wait until the writer release - // the lock - waitUninterruptibly(globalMutex); - } - } - } - + acquireForReaders(); } } } + /** + * Acquire the globalMutex lock on behalf of current and future concurrent readers. Make sure no writers currently + * owns the lock. + */ + private void acquireForReaders() { + // Try to get the globalMutex lock for the first reader + synchronized (globalMutex) { + // If the no one get the lock or the lock is locked by reader, just set the reference + // to the globalMutex to indicate that the lock is locked by Reader. + while (doesWriterOwnThisLock()) { + try { + globalMutex.wait(); + } catch (InterruptedException e) { + LOGGER.info("InterruptedException while waiting for globalMutex in acquireForReaders", e); + Thread.currentThread().interrupt(); + } + } + globalMutex.add(this); + } + } + @Override public void unlock() { @@ -179,23 +173,17 @@ public class ReaderWriterLock implements ReadWriteLock { synchronized (globalMutex) { - while (true) { - // When there is no one acquired the lock, just put the writeLock reference to the - // globalMutex to indicate that the lock is acquired by one writer. - // It is ensure that writer can only get the lock when no reader/writer acquired the lock. - if (isLockFree()) { - globalMutex.add(this); - break; - } else if (doesWriterOwnThisLock()) { - // Wait when other writer get the lock - waitUninterruptibly(globalMutex); - } else if (doesReaderOwnThisLock()) { - // Wait when other reader get the lock - waitUninterruptibly(globalMutex); - } else { - throw new AssertionError("it should never reach here"); + // Wait until the lock is free. + while (!isLockFree()) { + try { + globalMutex.wait(); + } catch (InterruptedException e) { + LOGGER.info("InterruptedException while waiting for globalMutex to begin writing", e); + Thread.currentThread().interrupt(); } } + // When the lock is free, acquire it by placing an entry in globalMutex + globalMutex.add(this); } } diff --git a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java index c468a61f8..dc379eef9 100644 --- a/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java +++ b/reader-writer-lock/src/main/java/com/iluwatar/reader/writer/lock/Writer.java @@ -22,11 +22,11 @@ */ package com.iluwatar.reader.writer.lock; +import java.util.concurrent.locks.Lock; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.locks.Lock; - /** * Writer class, write when it acquired the write lock */ @@ -37,10 +37,30 @@ public class Writer implements Runnable { private Lock writeLock; private String name; + + private long writingTime; + /** + * Create new Writer who writes for 250ms + * + * @param name - Name of the thread owning the writer + * @param writeLock - Lock for this writer + */ public Writer(String name, Lock writeLock) { + this(name, writeLock, 250L); + } + + /** + * Create new Writer + * + * @param name - Name of the thread owning the writer + * @param writeLock - Lock for this writer + * @param writingTime - amount of time (in milliseconds) for this reader to engage writing + */ + public Writer(String name, Lock writeLock, long writingTime) { this.name = name; this.writeLock = writeLock; + this.writingTime = writingTime; } @@ -50,18 +70,19 @@ public class Writer implements Runnable { try { write(); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.info("InterruptedException when writing", e); + Thread.currentThread().interrupt(); } finally { writeLock.unlock(); } } - + /** * Simulate the write operation */ public void write() throws InterruptedException { LOGGER.info("{} begin", name); - Thread.sleep(250); - LOGGER.info("{} finish", name); + Thread.sleep(writingTime); + LOGGER.info("{} finished after writing {}ms", name, writingTime); } } diff --git a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java index 30624a650..b8ad531ce 100644 --- a/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java +++ b/reader-writer-lock/src/test/java/com/iluwatar/reader/writer/lock/utils/InMemoryAppender.java @@ -52,6 +52,6 @@ public class InMemoryAppender extends AppenderBase { } public boolean logContains(String message) { - return log.stream().anyMatch(event -> event.getFormattedMessage().equals(message)); + return log.stream().anyMatch(event -> event.getFormattedMessage().contains(message)); } } diff --git a/singleton/README.md b/singleton/README.md index 4032ffaed..1be304d8e 100644 --- a/singleton/README.md +++ b/singleton/README.md @@ -15,7 +15,39 @@ tags: Ensure a class only has one instance, and provide a global point of access to it. -![alt text](./etc/singleton_1.png "Singleton") + +## Explanation +Real world example + +> There can only be one ivory tower where the wizards study their magic. The same enchanted ivory tower is always used by the wizards. Ivory tower here is singleton. + +In plain words + +> Ensures that only one object of a particular class is ever created. + +Wikipedia says + +> In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. + +**Programmatic Example** + +Joshua Bloch, Effective Java 2nd Edition p.18 + +> A single-element enum type is the best way to implement a singleton + +``` +public enum EnumIvoryTower { + INSTANCE; +} +``` + +Then in order to use + +``` +EnumIvoryTower enumIvoryTower1 = EnumIvoryTower.INSTANCE; +EnumIvoryTower enumIvoryTower2 = EnumIvoryTower.INSTANCE; +assertEquals(enumIvoryTower1, enumIvoryTower2); // true +``` ## Applicability Use the Singleton pattern when @@ -40,7 +72,7 @@ Use the Singleton pattern when * Violates Single Responsibility Principle (SRP) by controlling their own creation and lifecycle. * Encourages using a global shared instance which prevents an object and resources used by this object from being deallocated. -* Creates tightly coupled code that is difficult to test. +* Creates tightly coupled code. The clients of the Singleton become difficult to test. * Makes it almost impossible to subclass a Singleton. ## Credits diff --git a/singleton/etc/singleton.png b/singleton/etc/singleton.png deleted file mode 100644 index 0bf0c9b28..000000000 Binary files a/singleton/etc/singleton.png and /dev/null differ diff --git a/singleton/etc/singleton.ucls b/singleton/etc/singleton.ucls deleted file mode 100644 index 40c2ebd19..000000000 --- a/singleton/etc/singleton.ucls +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/singleton/etc/singleton.urm.puml b/singleton/etc/singleton.urm.puml deleted file mode 100644 index f61377e17..000000000 --- a/singleton/etc/singleton.urm.puml +++ /dev/null @@ -1,43 +0,0 @@ -@startuml -package com.iluwatar.singleton { - class App { - - LOGGER : Logger {static} - + App() - + main(args : String[]) {static} - } - enum EnumIvoryTower { - + INSTANCE {static} - + toString() : String - + valueOf(name : String) : EnumIvoryTower {static} - + values() : EnumIvoryTower[] {static} - } - class InitializingOnDemandHolderIdiom { - - InitializingOnDemandHolderIdiom() - + getInstance() : InitializingOnDemandHolderIdiom {static} - } - -class HelperHolder { - - INSTANCE : InitializingOnDemandHolderIdiom {static} - - HelperHolder() - } - class IvoryTower { - - INSTANCE : IvoryTower {static} - - IvoryTower() - + getInstance() : IvoryTower {static} - } - class ThreadSafeDoubleCheckLocking { - - instance : ThreadSafeDoubleCheckLocking {static} - - ThreadSafeDoubleCheckLocking() - + getInstance() : ThreadSafeDoubleCheckLocking {static} - } - class ThreadSafeLazyLoadedIvoryTower { - - instance : ThreadSafeLazyLoadedIvoryTower {static} - - ThreadSafeLazyLoadedIvoryTower() - + getInstance() : ThreadSafeLazyLoadedIvoryTower {static} - } -} -IvoryTower --> "-INSTANCE" IvoryTower -ThreadSafeDoubleCheckLocking --> "-instance" ThreadSafeDoubleCheckLocking -ThreadSafeLazyLoadedIvoryTower --> "-instance" ThreadSafeLazyLoadedIvoryTower -HelperHolder ..+ InitializingOnDemandHolderIdiom -HelperHolder --> "-INSTANCE" InitializingOnDemandHolderIdiom -@enduml \ No newline at end of file diff --git a/singleton/etc/singleton_1.png b/singleton/etc/singleton_1.png deleted file mode 100644 index 58dc440a9..000000000 Binary files a/singleton/etc/singleton_1.png and /dev/null differ diff --git a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java index 0b1b51b23..68f190d46 100644 --- a/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java +++ b/singleton/src/main/java/com/iluwatar/singleton/ThreadSafeLazyLoadedIvoryTower.java @@ -33,7 +33,12 @@ public final class ThreadSafeLazyLoadedIvoryTower { private static ThreadSafeLazyLoadedIvoryTower instance; - private ThreadSafeLazyLoadedIvoryTower() {} + private ThreadSafeLazyLoadedIvoryTower() { + // to prevent instantiating by Reflection call + if (instance != null) { + throw new IllegalStateException("Already initialized."); + } + } /** * The instance gets created only when it is called for first time. Lazy-loading diff --git a/tls/README.md b/tls/README.md index 02d889f50..3fb5e9a6b 100644 --- a/tls/README.md +++ b/tls/README.md @@ -19,4 +19,4 @@ Securing variables global to a thread against being spoiled by other threads. Th Use the Thread Local Storage in any of the following situations * when you use class variables in your Callable / Runnable object that are not read-only and you use the same Callable instance in more than one thread running in parallel. -* when you use static variables in your Callable / Runnable object that are not read-only and more than one instances of the Callable / Runnalbe may run in parallel threads. +* when you use static variables in your Callable / Runnable object that are not read-only and more than one instances of the Callable / Runnable may run in parallel threads.